1

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.

turivishal
  • 34,368
  • 7
  • 36
  • 59

2 Answers2

2

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);
hgb123
  • 13,869
  • 3
  • 20
  • 38
1

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • thank you for you answer, i know that but i want it in Date type, not in string, because want to pass in database. – turivishal Sep 11 '20 at 09:58