How to prevent changes on timestamp when convert from string to ISODate Javascript?

倾然丶 夕夏残阳落幕 提交于 2021-01-07 01:02:21

问题


I have a date in (yyyy-mm-dd) format, i want to get start and end date with timestamps and ISO format, i can concat date and timestamp but i want it in date type not in string,

let date = "2020-09-11";

Expected result should be,

startDate = 2020-09-11T00:00:00.000Z
endDate = 2020-09-11T23:59:59.000Z

The start date is correct, The end date is not correct, it gives different time stamp, 18:29:59.000Z when i set it to setHours(23,59,59),

let startDate = new Date(date);
console.log(startDate);
// output: 2020-09-11T00:00:00.000Z

let endDate = new Date(new Date(date).setHours(23,59,59)); 
console.log(endDate);
// output: 2020-09-11T18:29:59.000Z

I looked at this question convert string to ISO date time in nodejs, but this does not help me, i don't want to use moment,

Am i doing wrong to convert dates? i am using nodejs.


回答1:


You should use setUTCHours()

The setUTCHours() method sets the hour for a specified date according to universal time

let date = new Date()
let startDate = new Date(new Date(date).setUTCHours(0,0,0));
let endDate = new Date(new Date(date).setUTCHours(23,59,59));

console.log(startDate);
console.log(endDate);



回答2:


You could just add the postfix without conversion to a local date.

let date = "2020-09-11",
    startDate = date + 'T00:00:00.000Z',
    endDate = date + 'T23:59:59.000Z';

console.log(startDate);
console.log(endDate);


来源:https://stackoverflow.com/questions/63844762/how-to-prevent-changes-on-timestamp-when-convert-from-string-to-isodate-javascri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!