我希望用户输入日期。使用表单,并在后台将其转换为天数。然后消失一定天数,然后将其转换回日期。
示例:
输入您出生的日期。
- 转换为xx天数(dateindays)
然后make newtotal = dateindays-280
将newtotal转换为日期。
有人能指出我这样做的正确方向,还是他们知道这样做的一些功能?
让我们说:用户输入日期为1980年7月13日 我们使用js将其转换为总天数11,453天
然后创建新函数:subtotal = 11453-280
将这些天数转换为日期,并在屏幕上回显。
答案 0 :(得分:3)
使用Date对象。使用millis进行转换。因此,如果您获得日期毫秒,然后减去或添加天* 86400 * 1000,然后使用结果创建另一个日期对象。
var d2 = new Date (d1.getTime() - days_to_subtract * 86400 * 1000);
这可能会有所帮助...... http://www.w3schools.com/jsref/jsref_obj_date.asp
答案 1 :(得分:3)
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
然后使用以下链接对其进行格式化: http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
感谢这个链接的SO问题: Where can I find documentation on formatting a date in JavaScript?
答案 2 :(得分:2)
为什么转换为天?要添加或减去天数,只需在日期中添加或减去它们:
// 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