javascript 将日期转换为天数然后做一些事情
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8205539/
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
convert date to number of days then do stuff
提问by 422
I want user to enter a date. Using a form, and in the background convert this to number of days. Then desuct a certain number of days, then convert that back to a date.
我希望用户输入日期。使用表单,并在后台将其转换为天数。然后删除一定天数,然后将其转换回日期。
Example:
例子:
Enter the date you were born.
输入您的出生日期。
-- convert to xx amount of days (dateindays)
-- 转换为 xx 天数(dateindays)
Then make newtotal=dateindays-280
然后使 newtotal=dateindays-280
convert newtotal to a date.
将 newtotal 转换为日期。
Can anyone point me in the right direction of doing this, or do they know some function for doing this?
任何人都可以指出我这样做的正确方向,或者他们知道这样做的一些功能吗?
So lets say :user enters date 13th July 1980 We use js to convert this to total number of days 11,453 days
所以让我们说:用户输入日期 1980 年 7 月 13 日我们使用 js 将其转换为总天数 11,453 天
Then create new function : subtotal=11453-280
然后创建新函数:小计=11453-280
And convert those number of days into a date, and echo back on screen.
并将这些天数转换为日期,并在屏幕上回显。
回答by Sid Malani
use Date object. Use millis to do the conversion. So if you get the date millis and then subtract or add days * 86400 * 1000 and then create another date object with the result.
使用日期对象。使用millis进行转换。因此,如果您获得日期毫秒,然后减去或添加天数 * 86400 * 1000,然后使用结果创建另一个日期对象。
var d2 = new Date (d1.getTime() - days_to_subtract * 86400 * 1000);
This might help... http://www.w3schools.com/jsref/jsref_obj_date.asp
这可能会有所帮助... http://www.w3schools.com/jsref/jsref_obj_date.asp
回答by Chris
var d1 = Date.parse("13 July 1980");
d1 = d1 - 24192000000; // 280 days in milliseconds
var newDate = new Date(d1);
console.log(newDate); // will return a date object that represents Oct 07 1979
Then use the following link to format it: http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
然后使用以下链接对其进行格式化:http: //www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
Thanks to this SO question for the link: Where can I find documentation on formatting a date in JavaScript?
感谢链接的这个 SO 问题: 我在哪里可以找到有关在 JavaScript 中格式化日期的文档?
回答by RobG
Why the conversion to and from days? To add or subtract days, just add or subtract them from the date:
为什么转换为天?要添加或减去天数,只需从日期中添加或减去它们:
// New date object for 15 November, 2011
var d = new Date(2011, 10, 15);
// Add 5 days
d.setDate(d.getDate() + 5); // 20-Nov-2011
// Subract 200 days
d.setDate(d.getDate() - 200); // 4-May-2011