0

Why is getting the MMMM format on the first day of the month returning the previous month, but returning the correct month starting with the second day of the month, using this format 2020-08-01T00:00:00Z? Does it have to do with the timezone offset? Example case below:

With the first day of the month:

start = "2020-08-01T00:00:00Z";
month = moment(start).format("MMMM");
console.log(month) // <- July

With the second day of the month:

start = "2020-08-02T00:00:00Z";
month = moment(start).format("MMMM");
console.log(month) // <- August
critrange
  • 5,652
  • 2
  • 16
  • 47
ckingchris
  • 559
  • 1
  • 12
  • 25
  • 1
    Does this answer your question? [Why does js subtract a day from a Date object with a certain format?](https://stackoverflow.com/questions/28344408/why-does-js-subtract-a-day-from-a-date-object-with-a-certain-format) – Heretic Monkey Jul 27 '20 at 18:33
  • @HereticMonkey this is helpful, but the answer accepted below answers this particular question related to moment js – ckingchris Jul 27 '20 at 18:36

1 Answers1

1

Yes, this is because Moment objects are, by default, created in the local timezone. So if your local timezone is UTC minus anything and you create a moment with a midnight UTC time string, you will get the last day of the previous month.

To prevent this you can use utc(), parseZone(), a string that does not include the time, or you can specify the timezone using the moment-timezone package:

start = "2020-08-01T00:00:00Z";
month = moment(start).format("MMMM");
monthUTC = moment(start).utc().format("MMMM"); // or moment.utc(start).format("MMMM");
monthPZ = moment.parseZone(start).format("MMMM");
monthNoTime = moment("2020-08-01").format("MMMM");

// Note: Requires separate moment-timezone package
monthLA = moment(start).tz('America/Los_Angeles').format("MMMM");
monthSYD = moment(start).tz('Australia/Sydney').format("MMMM");

console.log("Default: ", month);
console.log("UTC: ", monthUTC);
console.log("parseZone: ", monthPZ);
console.log("No time: ", monthNoTime);
console.log("LA: ", monthLA);
console.log("Sydney: ", monthSYD);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>
jdaz
  • 5,964
  • 2
  • 22
  • 34