1

I am able to convert below object to moment

var dateStr = "Tue Dec 06 00:00:00 EDT 2022";
var momentDateFormatted = moment(dateStr).format("MM-DD-YYYY");
alert(momentDateFormatted);   //07-14-2014

But this doesnt work for below code

var dateStr1 = "Tue Dec 06 00:00:00 IST 2022"; 
var momentDateFormatted1 = moment(dateStr1).format("MM-DD-YYYY");
alert(momentDateFormatted1); // Invalid date

}

only difference is EDT and IST. nothing else.

Why would that not work? Any idea?

http://jsfiddle.net/markd116/kj5nzz4w/

Keshav
  • 1,123
  • 1
  • 18
  • 36

1 Answers1

2

The reason why the code doesn't work for the dateStr1 with the time zone "IST" is that the Moment.js library does not recognize the "IST" (Indian Standard Time) time zone abbreviation by default.

Moment.js has built-in support for a limited set of time zone abbreviations, and "IST" is not one of them.

To work with time zones in Moment.js, you typically need to use the Moment Timezone plugin, which extends Moment.js to handle various time zone conversions. This plugin provides a comprehensive time zone database that includes a wider range of time zone abbreviations and offsets.

An example:

// Parse and format the date string with the "IST" time zone using Moment Timezone
var dateStr1 = "Tue Dec 06 00:00:00 IST 2022";
var momentDateFormatted1 = moment.tz(dateStr1, "ddd MMM DD HH:mm:ss z YYYY", "Asia/Kolkata").format("MM-DD-YYYY");
alert(momentDateFormatted1); // 12-06-2022

In the above example, I use the moment.tz() function provided by the Moment Timezone plugin.

Edit:

// Parse the date string
var dateStr1 = "Tue Dec 06 00:00:00 IST 2022";
var momentDate1 = moment(dateStr1, "ddd MMM DD HH:mm:ss [GMT] Z YYYY");

// Format the date in the local time zone
var momentDateFormatted1 = momentDate1.local().format("MM-DD-YYYY");
alert(momentDateFormatted1);

In this code, first parse the date string using moment() and specify the input format, including the "IST" time zone offset. By default, Moment.js treats the provided time zone offset as UTC. Then, convert the parsed date to the local time zone using the local() method. Finally format the converted date string according to the desired format.

By using the local() method, the code will adapt to the time zone of the system executing it, providing the correct local date and time information.

This approach allows you to handle different time zones dynamically without hardcoding a specific time zone.

Mile Mijatović
  • 2,948
  • 2
  • 22
  • 41