javascript 我如何获得距离下一个生日还有多少天?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16484884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the how many days until my next birthday?
提问by BreezyChick89
I tried this but it fails
我试过这个,但它失败了
var diffDays1=(function(){
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date(new Date().getFullYear()+1,4,5);
var firstDate = new Date();
return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
})();
Wolfram alpha says it's 330 days, diffDays1 shows it's 359. This is probably due to daylight savings or something. Is there a way to accurately calculate days since without doing it server side.
Wolfram alpha 说它是 330 天,diffDays1 显示它是 359。这可能是由于夏令时或其他原因。有没有办法准确计算天数,因为没有在服务器端进行。
回答by user694844
The problem is that you're basing the month on April being 4, when April is 3 in Javascript. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date#Parameters
问题是,您将 4 月设为 4,而 JavaScript 中的 4 月为 3。请参阅https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date#Parameters
var diffDays1=(function(){
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var secondDate = new Date(new Date().getFullYear()+1,3,5);
var firstDate = new Date();
return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
})();
回答by aorlando
回答by andrunix
The moment.js library (http://momentjs.com) handles this and a lot of other JavaScript date issues very easily and nicely. The diff function (http://momentjs.com/docs/#/displaying/difference/) will do exactly what you want.
moment.js 库 ( http://momentjs.com) 可以非常轻松和良好地处理这个和许多其他 JavaScript 日期问题。diff 函数 ( http://momentjs.com/docs/#/displaying/difference/) 将完全符合您的要求。
The fromNow function is also super nice if want to display the number of days from now you could do something like:
如果想显示从现在开始的天数, fromNow 函数也非常好,您可以执行以下操作:
moment([2014, 4, 5]).fromNow();
would produce something like "330 days" if it's 330 days away.
如果距离 330 天,则会产生类似“330 天”的内容。
回答by LStarky
Here's a cleaner solution using moment, which handles all cases correctly (including today, upcoming birthday this year or not until next year, time zone, leap year, etc.):
这是使用 moment 的更清洁的解决方案,它可以正确处理所有情况(包括今天、今年即将到来的生日或直到明年、时区、闰年等):
const birthdate = '2018-12-15';
const today = moment().format('YYYY-MM-DD');
const years = moment().diff(birthdate, 'years');
const adjustToday = birthdate.substring(5) === today.substring(5) ? 0 : 1;
const nextBirthday = moment(birthdate).add(years + adjustToday, 'years');
const daysUntilBirthday = nextBirthday.diff(today, 'days');
Simple, fast, accurate!
简单、快速、准确!
Here's the same code, explained:
这是相同的代码,解释如下:
// This is the birthdate we're checking, in ISO 8601 format
const birthdate = '2018-12-15';
// Get today's date in ISO 8601 format
const today = moment().format('YYYY-MM-DD');
// Calculate current age of person in years (moment truncates by default)
const years = moment().diff(birthdate, 'years');
// Special case if birthday is today; we do NOT need an extra year added
const adjustToday = birthdate.substring(5) === today.substring(5) ? 0 : 1;
// Add age plus one year (unless birthday is today) to get next birthday
const nextBirthday = moment(birthdate).add(years + adjustToday, 'years');
// Final calculation in days
const daysUntilBirthday = nextBirthday.diff(today, 'days');
If the birthday is today, the result will be 0; if it is tomorrow, the result will be 1, and so on.
如果生日是今天,则结果为 0;如果是明天,结果将是 1,依此类推。
回答by Lucas Janon
The selected solution doesn't work if the birthday is this year, because it sums 1 to getFullYear.
如果生日是今年,则所选解决方案不起作用,因为 getFullYear 的总和为 1。
This is my solution, it also prevents two edge cases: birthday today and 1 day remaining.
这是我的解决方案,它还可以防止两种边缘情况:今天生日和剩余 1 天。
const birthdayDay = 19;
const birthdayMonth = 11; // december === 11
const myBirthdayThisYear = new Date(new Date().getFullYear(), 11, 19).setHours(23, 59, 59);
export const daysUntilBirthday = () => {
const addToYear = myBirthdayThisYear > Date.now() ? 0 : 1;
const oneDay = 24 * 60 * 60 * 1000;
const secondDate = new Date(new Date().getFullYear() + addToYear, birthdayMonth, birthdayDay);
const firstDate = new Date();
const days = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
const daysOrDay = days === 1 ? 'day' : 'days';
return days !== 365 ? `${days} ${daysOrDay} until my birthday ` : ' TODAY IS MY BIRTHDAY ';
};