4 回答
TA贡献1793条经验 获得超6个赞
最好先从当前日期中减去指定日期的毫秒数,然后将其格式化为您想要的输出。
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,因为它更可靠并且有大量内置方法会让你的生活更轻松。
TA贡献1788条经验 获得超4个赞
可能你可能想检查 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>
TA贡献1744条经验 获得超4个赞
原始解决方案可在此处找到: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/dayjs
Step 2 : Save the downloaded file to the Drafts/Library/Scripts folder in iCloud.
*/
require('dayjs.min.js'); // Tell Drafts to use Dayjs script
let dPast = 'December 4, 2017'; // set the date from the past
let d1 = dayjs(); // tell Dayjs to parse the date
let 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.
}
/* Remainder
An 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.
}
}
TA贡献1812条经验 获得超5个赞
这段代码经过测试可以运行,可以精确到分钟。
/**
* 计算日期&时间间隔/推算几天前后是哪一天
* @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 = number
const 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 }
添加回答
举报