计算自特定日期以来的年月

我刚开始使用 Java Script。我正在尝试提出一个简单的解决方案:


当前日期 - 格式为“2018 年 1 月 4 日”的指示日期 = 自指示日期以来的年月。


我查看了Datejs,但无法弄清楚如何使用它来进行简单的数学日期计算。


我想出了这个,但我不确定这是否是可行的方法。欢迎提出建议。


var dPast = 'January 4, 2018'

var d1 = new Date(); //"now"

var d2 = new Date(dPast);

var dCalc = Math.abs((d1-d2)/31556952000);   // difference in milliseconds

var diff = Math.round(10 * dCalc)/10;   // difference in years rounded to tenth


alert('It has been ' + diff + ' years since ' + dPast);


森栏
浏览 237回答 4
4回答

摇曳的蔷薇

最好先从当前日期中减去指定日期的毫秒数,然后将其格式化为您想要的输出。var dPast = 'January 5, 2018';var indicatedD = new Date(dPast);var d = new Date();// subtract the current time's milliseconds from the dPast date's.var elapsed = new Date(d.getTime() - indicatedD.getTime());// get the years.var years = Math.abs(elapsed.getUTCFullYear() - 1970);console.log('It has been ' + years + ' years since ' + dPast);因为你刚刚起步,所以最好自己探索,但当你适应后,我建议你使用日期库,例如moment.js,因为它更可靠并且有大量内置方法会让你的生活更轻松。

尚方宝剑之说

可能你可能想检查 moment.js。它只有 2.6kb 大小,或者你可以使用 cdn<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>检查diff功能var dPast = 'January 4, 2018'var todaysDate = moment(new Date()); //"now"var pastDate = moment(new Date(dPast));var years = todaysDate.diff(pastDate, 'years');var months = todaysDate.diff(pastDate, 'months');console.log(years + ' years, ' + months % 12 + ' months');<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

慕无忌1623718

原始解决方案可在此处找到:https ://forums.getdrafts.com/t/calculate-years-and-months-since-a-specific-date/8082/3这段代码是一个进步,因为我想让初学者的事情变得简单。然而,我是一步一步去理解的。我会在这里留下足迹,供我自己参考,也供以后的人参考。/*********Day.js is a minimalist JavaScript library that parses, validates, manipulates, and displays dates and times for modern browsers with a largely Moment.js-compatible API.Step 1: Download the dayjs.min.js file from the JSDelivr site: https://www.jsdelivr.com/package/npm/dayjsStep 2 : Save the downloaded file to the Drafts/Library/Scripts folder in iCloud.&nbsp;*/require('dayjs.min.js'); // Tell Drafts to use Dayjs scriptlet dPast = 'December 4, 2017'; // set the date from the pastlet d1 = dayjs(); // tell Dayjs to parse the datelet d2 = dayjs(dPast); // set the current date/******* Math.round() - is a function that is used to return a number rounded to the nearest integer (whole) value.* To get the difference in months, pass the month as the second argument. By default, dayjs#diff will truncate the result to zero decimal places, returning an integer. If you want a floating point number, pass true as the third argument.*Read more: https://day.js.org/docs/en/display/difference#docsNav*/let m = Math.round(d1.diff(d2, 'month', true));/******* Divide the number of months (obtained earlier) by 12 to see how many years. This number will be rounded to an integer (whole number). If the result is less than 1 (years) the rounded number will be set to 0. For example 11/12 = 0.916666667 This will be rounded to 0.*/let y = Math.floor(m/12);&nbsp;if (y == 0) {&nbsp; alert(`\n${m} months since ${dPast}`); // Alert that "x" number of months but no years have passed since the indicated date.}/* RemainderAn amount left over after division (happens when the first number does not divide exactly by the other). Example: 19 cannot be divided exactly by 5. The closest you can get without going over is 3 x 5 = 15, which is 4 less than 19. So 4 is the remainder.In JavaScript, the remainder operator (%) returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.*/else {&nbsp; m = m % 12;&nbsp; if (m == 0) {&nbsp; &nbsp; alert(`${y} years since ${dPast}`); //If the remainder is 0 than a whole year(s) have passed since the indicated date but no months.&nbsp; }&nbsp; else {&nbsp; &nbsp; alert(`${y} years, ${m} months since ${dPast}`); // Years and months since the indicated date.&nbsp; }}

ABOUTYOU

这段代码经过测试可以运行,可以精确到分钟。/**&nbsp;* 计算日期&时间间隔/推算几天前后是哪一天&nbsp;* @author 江村暮&nbsp;*///平年const ordinaryYearMonth: Array<any> = [null, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]//闰年const leapYearMonth: Array<any> = [null, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]/**&nbsp;* 是否为闰年&nbsp;**/const isLeap = (year: number): boolean => {&nbsp; &nbsp; if (year % 400 === 0 && year % 100 === 0) return true&nbsp; &nbsp; if (year % 4 === 0 && year % 100 !== 0) return true&nbsp; &nbsp; return false}//解析时间串type Num = numberconst parseTime = (time: string): {&nbsp; &nbsp; hour: Num;&nbsp; &nbsp; min: Num} => {&nbsp; &nbsp; var bound: Num = time.indexOf(':')&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; hour: parseInt(time.substring(0, bound)),&nbsp; &nbsp; &nbsp; &nbsp; min: parseInt(time.substring(bound + 1))&nbsp; &nbsp; }}//解析日期串const parseDate = (date = '2020-03-06'): Readonly<{&nbsp; &nbsp; year: number;&nbsp; &nbsp; month: number;&nbsp; &nbsp; day: number;&nbsp; &nbsp; isLeap: boolean}> => {&nbsp; &nbsp; var match = /(\d{4})-(\d{2})-(\d{2})/.exec(date);&nbsp; &nbsp; if (!match) throw Error&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; year: parseInt(match[1]),&nbsp; &nbsp; &nbsp; &nbsp; month: parseInt(match[2].replace(/^0/, '')),&nbsp; &nbsp; &nbsp; &nbsp; day: parseInt(match[3].replace(/^0/, '')),&nbsp; &nbsp; &nbsp; &nbsp; isLeap: isLeap(parseInt(match[1]))&nbsp; &nbsp; }}const calDiffer = (&nbsp; &nbsp; defaultDateEarly: string,&nbsp; &nbsp; defaultDateLate: string,&nbsp; &nbsp; defaultTimeEarly?: string,&nbsp; &nbsp; defaultTimeLate?: string): {&nbsp; &nbsp; day: number,&nbsp; &nbsp; hour: number,&nbsp; &nbsp; min: number,&nbsp; &nbsp; overflowHour: number,&nbsp; &nbsp; overflowMin: number} => {&nbsp; &nbsp; var dateEarly = parseDate(defaultDateEarly)&nbsp; &nbsp; &nbsp; &nbsp; , dateLate = parseDate(defaultDateLate)&nbsp; &nbsp; &nbsp; &nbsp; , diffDay: number;&nbsp; &nbsp; //两个日期在同一年&nbsp; &nbsp; if (dateLate.year === dateEarly.year) {&nbsp; &nbsp; &nbsp; &nbsp; var numOfEarlyMonthDay = dateEarly.isLeap ? leapYearMonth[dateEarly.month] : ordinaryYearMonth[dateEarly.month]&nbsp; &nbsp; &nbsp; &nbsp; // 两个日期在同一月份&nbsp; &nbsp; &nbsp; &nbsp; if (dateLate.month === dateEarly.month) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; diffDay = dateLate.day - dateEarly.day&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; diffDay = dateLate.day + numOfEarlyMonthDay - dateEarly.day;//两个日期所在月的非整月天数和&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (let i = dateEarly.month; i < dateLate.month - 1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; diffDay += (dateLate.isLeap) ? leapYearMonth[i] : ordinaryYearMonth[i]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; //这一年已过天数&nbsp; &nbsp; &nbsp; &nbsp; var lateYearDay = dateLate.day;&nbsp; &nbsp; &nbsp; &nbsp; for (let i = dateLate.month - 1; i >= 1; i--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lateYearDay += (dateLate.isLeap) ? leapYearMonth[i] : ordinaryYearMonth[i]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; console.log(lateYearDay)&nbsp; &nbsp; &nbsp; &nbsp; //那一年剩下天数&nbsp; &nbsp; &nbsp; &nbsp; var earlyYearDay = 0&nbsp; &nbsp; &nbsp; &nbsp; for (let i = 13 - dateEarly.month; i >= 1; i--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; earlyYearDay += (dateLate.isLeap) ? leapYearMonth[i] : ordinaryYearMonth[i]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; earlyYearDay -= dateEarly.day&nbsp; &nbsp; &nbsp; &nbsp; console.log(earlyYearDay)&nbsp; &nbsp; &nbsp; &nbsp; //相隔年份天数,如:年份为2010 - 2020,则计算2011 - 2019的天数&nbsp; &nbsp; &nbsp; &nbsp; var diffYear: number[] = [];&nbsp; &nbsp; &nbsp; &nbsp; for (let i = 0; i <= dateLate.year - dateEarly.year - 1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; diffYear.push(dateEarly.year + i + 1)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; diffDay = earlyYearDay + lateYearDay&nbsp; &nbsp; &nbsp; &nbsp; diffYear.map(year => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; diffDay += isLeap(year) ? 366 : 365&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; }&nbsp; &nbsp; //计算这天剩下的时间与那天已经过的分钟之和&nbsp; &nbsp; var timeEarly = parseTime(defaultTimeEarly || '00:00'),&nbsp; &nbsp; &nbsp; &nbsp; timeLate = parseTime(defaultTimeLate || '00:00');&nbsp; &nbsp; var overflowDiffMin = 60 * (25 - timeEarly.hour + timeLate.hour) + 60 - timeEarly.min + timeLate.min&nbsp; &nbsp; var diffMin = (diffDay - 1) * 1440 + overflowDiffMin&nbsp; &nbsp; console.log(timeEarly, timeLate, diffMin)&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; day: diffDay,&nbsp; &nbsp; &nbsp; &nbsp; overflowHour: Math.floor(diffMin/60) - diffDay * 24,&nbsp; &nbsp; &nbsp; &nbsp; overflowMin: diffMin % 60,//(overflowDiffMin - 1440 * diffDay) % 60,&nbsp; &nbsp; &nbsp; &nbsp; hour: Math.floor(diffMin/60),&nbsp; &nbsp; &nbsp; &nbsp; min: diffMin % 60&nbsp; &nbsp; }}export { calDiffer }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript