2

I was expecting the following to return 2020-01-01T23:59:59
But due to my time zone being GMT+2, it results in this 2020-01-01T21:59:59.

How do I represent the end of the day as 23:59:59 from a date that is parsed using moment.js

var date = moment("2020-01-01").endOf("day").toDate();
Jim
  • 14,952
  • 15
  • 80
  • 167
  • Are you okay with hackey solutions? because you could set the time to midday, print out the Y-m-d format, and then just add `'T23:59:59'` to the end – TKoL Aug 03 '20 at 14:27
  • But that won't work if you have other reasons for wanting to do this sort of 'timezone normalizing' your'e talking about – TKoL Aug 03 '20 at 14:27
  • `var date = moment.utc("2020-01-01").endOf("day").toDate().toISOString();` – Heretic Monkey Aug 03 '20 at 14:29
  • Or, if you want to do it without moment, in the current timezone, `var date = new Date(2020, 0, 2); date = new Date(date.valueOf() - 1);` – Heretic Monkey Aug 03 '20 at 14:32
  • See also [this answer](https://stackoverflow.com/a/54004222/215552) – Heretic Monkey Aug 03 '20 at 14:34

2 Answers2

2

Ciao try to call .utc in moment like:

var date = moment("2020-01-01").utc().endOf("day").toDate();
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
0

I would keep the date as a moment object, up until you need to display it. Just simply call format on the object.

console.log(moment.utc('2020-01-01').endOf('day').format('YYYY-MM-DDTHH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132