慕无忌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. */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); if (y == 0) { 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 { m = m % 12; if (m == 0) { alert(`${y} years since ${dPast}`); //If the remainder is 0 than a whole year(s) have passed since the indicated date but no months. } else { alert(`${y} years, ${m} months since ${dPast}`); // Years and months since the indicated date. }}
ABOUTYOU
这段代码经过测试可以运行,可以精确到分钟。/** * 计算日期&时间间隔/推算几天前后是哪一天 * @author 江村暮 *///平年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]/** * 是否为闰年 **/const isLeap = (year: number): boolean => { if (year % 400 === 0 && year % 100 === 0) return true if (year % 4 === 0 && year % 100 !== 0) return true return false}//解析时间串type Num = numberconst parseTime = (time: string): { hour: Num; min: Num} => { var bound: Num = time.indexOf(':') return { hour: parseInt(time.substring(0, bound)), min: parseInt(time.substring(bound + 1)) }}//解析日期串const parseDate = (date = '2020-03-06'): Readonly<{ year: number; month: number; day: number; isLeap: boolean}> => { var match = /(\d{4})-(\d{2})-(\d{2})/.exec(date); if (!match) throw Error return { year: parseInt(match[1]), month: parseInt(match[2].replace(/^0/, '')), day: parseInt(match[3].replace(/^0/, '')), isLeap: isLeap(parseInt(match[1])) }}const calDiffer = ( defaultDateEarly: string, defaultDateLate: string, defaultTimeEarly?: string, defaultTimeLate?: string): { day: number, hour: number, min: number, overflowHour: number, overflowMin: number} => { var dateEarly = parseDate(defaultDateEarly) , dateLate = parseDate(defaultDateLate) , diffDay: number; //两个日期在同一年 if (dateLate.year === dateEarly.year) { var numOfEarlyMonthDay = dateEarly.isLeap ? leapYearMonth[dateEarly.month] : ordinaryYearMonth[dateEarly.month] // 两个日期在同一月份 if (dateLate.month === dateEarly.month) { diffDay = dateLate.day - dateEarly.day } else { diffDay = dateLate.day + numOfEarlyMonthDay - dateEarly.day;//两个日期所在月的非整月天数和 for (let i = dateEarly.month; i < dateLate.month - 1; i++) { diffDay += (dateLate.isLeap) ? leapYearMonth[i] : ordinaryYearMonth[i] } } } else { //这一年已过天数 var lateYearDay = dateLate.day; for (let i = dateLate.month - 1; i >= 1; i--) { lateYearDay += (dateLate.isLeap) ? leapYearMonth[i] : ordinaryYearMonth[i] } console.log(lateYearDay) //那一年剩下天数 var earlyYearDay = 0 for (let i = 13 - dateEarly.month; i >= 1; i--) { earlyYearDay += (dateLate.isLeap) ? leapYearMonth[i] : ordinaryYearMonth[i] } earlyYearDay -= dateEarly.day console.log(earlyYearDay) //相隔年份天数,如:年份为2010 - 2020,则计算2011 - 2019的天数 var diffYear: number[] = []; for (let i = 0; i <= dateLate.year - dateEarly.year - 1; i++) { diffYear.push(dateEarly.year + i + 1) } diffDay = earlyYearDay + lateYearDay diffYear.map(year => { diffDay += isLeap(year) ? 366 : 365 }) } //计算这天剩下的时间与那天已经过的分钟之和 var timeEarly = parseTime(defaultTimeEarly || '00:00'), timeLate = parseTime(defaultTimeLate || '00:00'); var overflowDiffMin = 60 * (25 - timeEarly.hour + timeLate.hour) + 60 - timeEarly.min + timeLate.min var diffMin = (diffDay - 1) * 1440 + overflowDiffMin console.log(timeEarly, timeLate, diffMin) return { day: diffDay, overflowHour: Math.floor(diffMin/60) - diffDay * 24, overflowMin: diffMin % 60,//(overflowDiffMin - 1440 * diffDay) % 60, hour: Math.floor(diffMin/60), min: diffMin % 60 }}export { calDiffer }