Reputation: 7856
I have an input 'Fri Aug 16 16:06:38 CDT 2019'
expected output is 4:06 PM Friday
assuming I am in Central Time Zone
expected output for Some one in Eastern Timezone is 5:06 PM Friday
I just get an error in the below snippet
const input = 'Fri Aug 16 16:06:38 CDT 2019';
const date = moment(input).format('dddd MMM DD HH:MM:SS ZZZ YYYY');
console.log('date', date);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>
not a duplicate of this
Upvotes: 0
Views: 481
Reputation: 106365
In this case, you need a format to tell moment
how to parse the datestring provided, not how to display it. For that purpose, you should use moment
constructor with two parameters - String + Format.
And don't forget that format is case-sensitive. MM
is a code for month, so you should use mm
instead to parse minutes (and ss
for seconds). As for output, you need to call local()
on the given date object to use local time to display a moment instead of the original moment's time.
However, there's another caveat here: momentjs
doesn't know how to process abbreviated offsets (like CDT, PST and so on) in this type of workflow; it only supports their subset in RFC2822 parsing workflow since this PR.
You can implement it on your own, of course, using the table in that request to replace the abbreviations with timezone offsets, then proceed with ZZ
flag. Like this:
const replaceAbbr = (() => dtstr => {
const rfc2822Timezones = {
' GMT': ' +0000',
' EDT': ' -0400',
' EST': ' -0500',
' CDT': ' -0500',
' CST': ' -0600',
' MDT': ' -0600',
' MST': ' -0700',
' PDT': ' -0700',
' PST': ' -0800'
};
return dtstr.replace(/ [A-Z]{2}T/, abbr => rfc2822Timezones[abbr] || abbr);
})();
const input = 'Fri Aug 16 16:06:38 CDT 2019';
const inputWithTz = replaceAbbr(input);
const date = moment(inputWithTz, 'ddd MMM DD HH:mm:ss ZZ YYYY', 'en');
console.log('output in UTC: ', date.utc().format('h:mm A dddd'));
// output in UTC: 9:06 PM Friday
console.log('output in local: ', date.local().format('h:mm A dddd'));
// depends
<script src="https://momentjs.com/downloads/moment.min.js"></script>
I actually have used a third parameter here to specify the locale, just in case it's not 'en'. Locale is used to parse both day-of-week and month value here.
Upvotes: 1
Reputation: 3108
Use the following format :
const input = 'Fri Aug 16 16:06:38 CDT 2019';
const date = moment(input).format('hh:mm A dddd');
console.log('date', date);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>
Upvotes: 1