-1

I want to get a date independent of timezone offset

const dateOne = moment('Thu Oct 20 2019 12:00:00 GMT-1200').format('YYYY/MM/DD'); // 2019/10/21
const dateTwo = moment('Thu Oct 20 2019 12:00:00 GMT+2300').format('YYYY/MM/DD'); // 2019/10/19

But I need to get 2019/10/20 for both cases. JS Date and moment as well are formatting a date with influence of GMT offset. How to avoid it?

Dzmitry Vasilevsky
  • 1,295
  • 2
  • 14
  • 25
  • you can just add your timezone offset into date's valueOf() to make UTC look local. – dandavis Oct 23 '19 at 16:19
  • https://momentjs.com/docs/#/manipulating/utc/ – Prerak Sola Oct 23 '19 at 16:21
  • parseZone is worked for me actually – Dzmitry Vasilevsky Oct 23 '19 at 16:32
  • Where is GMT+2300? – RobG Oct 23 '19 at 20:32
  • If you don't want the time or timezone, then trim them: `moment('Thu Oct 20 2019 12:00:00 GMT-1200'.slice(0,12)).format('YYYY/MM/DD')` – RobG Oct 24 '19 at 04:36
  • @RobG It's an option but I don't want to be bound to specific date format. The date here is coming from third-party datepicker plugin and if they change it's format slicing will fail – Dzmitry Vasilevsky Oct 24 '19 at 08:30
  • @DzmitryVasilevsky—if you don't know the format, you can't reliably parse the string regardless of the method you use. PS when you parse a string with moment.js and it's not one of it's supported formats, it falls back to the built–in parser, so you're really no better than `new Date(string)`. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Oct 24 '19 at 10:39
  • @RobG yeah, but moment accepts a variety of formats at least the most popular ones. like default toString() and toISOString, etc. – Dzmitry Vasilevsky Oct 24 '19 at 11:25
  • @DzmitryVasilevsky—those formats are also supported by the built–in parser. The point is that if you don't know the format, you also don't know whether it's supported by whatever parser you're using or not. It's always best to provide the format to the parser (see [*moment.js documentation*](https://momentjs.com/guides/#/parsing/known-formats/), in particular [strict mode](https://momentjs.com/guides/#/parsing/strict-mode/)), which infers not using the built–in parser because it doesn't take a format argument. – RobG Oct 25 '19 at 00:10

1 Answers1

1

moment.parseZone method worked for me

const date1 = moment.parseZone('Thu Oct 20 2019 12:00:00 GMT-1200').format('YYYY-MM-DD');
const date2 = moment.parseZone('Thu Oct 20 2019 12:00:00 GMT+2300').format('YYYY-MM-DD');
console.log(date1 === date2); // true
Dzmitry Vasilevsky
  • 1,295
  • 2
  • 14
  • 25