Moment.js - 반올림하지 않고 날짜 이후의 연도를 얻으려면 어떻게 해야 합니까?
Moment.js를 사용하여 사람의 나이를 계산하려고 하지만, Now 메서드에서 그렇지 않으면 유용하다는 것을 알게 되었습니다.예를 들어, 오늘이 2012년 12월 27일이고, 그 사람의 생년월일이 1978년 02월 26일인 경우,moment("02/26/1978", "MM/DD/YYYY").fromNow()'35년 전'을 반환합니다.Moment.js가 월 수를 무시하고 날짜 이후의 년 수(예: 34)를 간단히 반환하도록 하려면 어떻게 해야 합니까?
moment.js를 사용하는 것은 다음과 같이 쉽습니다.
var years = moment().diff('1981-01-01', 'years');
var days = moment().diff('1981-01-01', 'days');
추가 참고용으로 moment.js 공식 문서를 읽을 수 있습니다.
분수 값을 원하지 않는 경우:
var years = moment().diff('1981-01-01', 'years',false);
alert( years);
분수 값을 원하는 경우:
var years = moment().diff('1981-01-01', 'years',true);
alert( years);
단위는 [초, 분, 시간, 일, 주, 월, 년]일 수 있습니다.
결과를 반올림하지 않는 옵션뿐만 아니라 사용할 시간 간격을 수용하는 차이 함수가 있는 것으로 보입니다.그래서 뭔가.
Math.floor(moment(new Date()).diff(moment("02/26/1978","MM/DD/YYYY"),'years',true)))
나는 이것을 시도해 본 적이 없고, 순간에 완전히 익숙하지는 않지만, 이것은 (월을 재설정할 필요 없이) 당신이 원하는 것을 얻을 수 있을 것 같습니다.
이 방법은 쉽고 강력합니다.
값은 날짜이고 "DD-MM-YYYYY"는 날짜의 마스크입니다.
moment().diff(moment(value, "DD-MM-YYYY"), 'years');
두 날짜(제공된 날짜 및 현재) 모두 월을 1월로 재설정하는 것이 가능하다는 것을 알았습니다.
> moment("02/26/1978", "MM/DD/YYYY").month(0).from(moment().month(0))
"34 years ago"
시도해 보기:
moment("02/26/1978", "MM/DD/YYYY").fromNow().split(" ")[0];
설명:
우리는 '23일 전'과 같은 문자열을 받습니다.배열: ['23', 'days', 'ago']로 나눈 후 첫 번째 항목 '23'을 가져갑니다.
이 방법은 저에게 효과가 있습니다.올해 생일을 맞은 사람인지, 아니면 1년을 뺀 사람인지 확인하는 것입니다.
// date is the moment you're calculating the age of
var now = moment().unix();
var then = date.unix();
var diff = (now - then) / (60 * 60 * 24 * 365);
var years = Math.floor(diff);
편집: 첫 번째 버전은 완벽하게 작동하지 않았습니다.업데이트된 것은
연령 계산을 위해 모듈을 사용하지 않으려는 경우
var age = Math.floor((new Date() - new Date(date_of_birth)) / 1000 / 60 / 60 / 24 / 365.25)
연도와 남은 날짜를 표시하려는 경우:
var m = moment(d.birthday.date, "DD.MM.YYYY");
var years = moment().diff(m, 'years', false);
var days = moment().diff(m.add(years, 'years'), 'days', false);
alert(years + ' years, ' + days + ' days');
얻다years그리고.daysmoment.js 라이브러리 사용
import moment from 'moment'
export function getAge(dateString: string) {
const date = moment(dateString, 'YYYY-MM-DD')
const years = moment().diff(date, 'years')
const days = moment().diff(date.add(years, 'years'), 'days', false)
return { years, days }
}
const birthDate = "1997-04-01T00:00:00.000Z";
const age = getAge(birthDate);
// Today is 2022-04-09
console.log({ age })
// Result: { age: { years: 25, days: 8 } }
다음을 시도해 볼 수 있습니다.
moment
.duration({
years: moment(Date.now()).diff(datetime, "years", false),
})
.humanize()
저는 이 작은 방법이 더 좋습니다.
function getAgeFromBirthday(birthday) {
if(birthday){
var totalMonths = moment().diff(birthday, 'months');
var years = parseInt(totalMonths / 12);
var months = totalMonths % 12;
if(months !== 0){
return parseFloat(years + '.' + months);
}
return years;
}
return null;
}
여기 moment.js를 이용한 간단한 것이 있습니다.
let dt = dob;
let age = '';
let bY = Number(moment(dt).format('YYYY'));
let bM = Number(moment(dt).format('MM'));
let bD = Number(moment(dt).format('DD'));
let tY = Number(moment().format('YYYY'));
let tM = Number(moment().format('MM'));
let tD = Number(moment().format('DD'));
age += (tY - bY) + ' Y ';
if (tM < bM) {
age += (tM - bM + 12) + ' M ';
tY = tY - 1;
} else {
age += (tM - bM) + ' M '
}
if (tD < bD) {
age += (tD - bD + 30) + ' D ';
tM = tM - 1;
} else {
age += (tD - bD) + ' D '
}
//AGE MONTH DAYS
console.log(age);
언급URL : https://stackoverflow.com/questions/14057497/moment-js-how-do-i-get-the-number-of-years-since-a-date-not-rounded-up
'programing' 카테고리의 다른 글
| 레이아웃 제약 조건을 언제 활성화/비활성화할 수 있습니까? (0) | 2023.09.26 |
|---|---|
| WP 미디어 라이브러리 그리드 보기가 표시되지 않음 (0) | 2023.09.26 |
| 어떤 상황에서 malloc이 NULL을 반환할 수 있습니까? (0) | 2023.09.26 |
| jQuery Refresh/Ajax Success가 예상 시간 이후인 경우 페이지 다시 로드 (0) | 2023.09.26 |
| 머리글만 컬을 통해 php로 검색 (0) | 2023.09.26 |