简体   繁体   English

增加日期 Object 而不转换为 Javascript 中的纪元

[英]Increment Date Object in without converting to epoch in Javascript

Is it possible to increment a date object by one day without converting the object to an epoch number?是否可以将日期 object 增加一天而不将 object 转换为纪元编号?

For example the traditional way will convert the date object to an epoch number:例如,传统方式会将日期 object 转换为纪元数:

var today = new Date();
var tomorrow = new Date(today.valueOf()); // copy date object without converting to epoch
tomorrow.setDate(tomorrow.getDate() + 1); // now gets converted to epoch :'(

The set* methods don't "convert to epoch number", they modify the date's internal time value and return the modified value. set*方法不会“转换为纪元数”,它们会修改日期的内部时间值并返回修改后的值。 The date object is still a date.日期 object 仍然是一个日期。

 let today = new Date(); today.setHours(0,0,0,0); // Start of day let tvToday = +today; let tomorrow = new Date(today); // setDate adjusts the time value and returns it let tvTomorrow = tomorrow.setDate(tomorrow.getDate() + 1); console.log('Today\'s date: ' + today.toDateString()); console.log('Today\'s time value: ' + tvToday); console.log('Tomorrow\'s date: ' + tomorrow.toDateString()); console.log('Tomorrow\'s time value: ' + tvTomorrow); // May vary from 24 by up to 1 hour depending on crossing DST boundaries console.log('Difference in hours: ' + ((tvTomorrow - tvToday)/3.6e6));

If you want a method that adds a day and returns a new Date object, write a function, maybe named addDays , that takes a date and number of days to add and returns a new Date object with the days added.如果您想要一个添加一天并返回新日期 object 的方法,请编写一个 function,可能命名为addDays ,它需要一个日期和天数来添加并返回一个新的日期 ZA8CFDE6331BD59EB2666F8911ZCB Lots of libraries have such functions, they're not hard to write.很多库都有这样的功能,不难写。

Not sure if you can do that without converting.不知道你是否可以在不转换的情况下做到这一点。 Maybe convert back after.也许之后转换回来。

 var today = new Date(); var tomorrow = new Date(today.valueOf()); const x = tomorrow.setDate(tomorrow.getDate() + 1); console.log(x) //epoch const z = new Date(x) console.log(z.toString())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM