0

I've looked at these posts - along with reading the docs; Create a local date from a UTC date string in Moment.js and Changing the Utc Date to Local Date using moment.js

And I still don't quit get what I want.

All dates in the DB are stored in UTC, but I want the client to see dates in their local time - BUT WITH THE TIME ZONE.

I can get the .local(), but that shaves the zone info, I can get the result I want IF I specify the time zone, but I'm not going to KNOW the time zone... Isn't that one of the things moment/timezone is supposed to give? I can get the offset - but the docs don't say how to use that.

Example (this is what I'm going for): Sep 8th 15, 10:51 pm CDT

Here's a sample of what I've tried.

// I spoof a date as if it came from the db (for demo purposes)
var now = new Date().toUTCString();

// now outputs.. I am in CDT (-0500)
document.write( now ); 
    // Wed, 09 Sep 2015 03:51:15 GMT

document.write( moment( now ).format('MMM Do YY, h:mm a z') );
    // Sep 8th 15, 10:51 pm

document.write( moment( now ).local().format('MMM Do YY, h:mm a z') );
    // Sep 8th 15, 10:51 pm  (same as above, so I'm unclear what 'local()' gives me that I didn't already have?)

document.write( moment( now ).tz('America/Chicago').format('MMM Do YY, h:mm a z') );
    // Sep 8th 15, 10:51:15 pm CDT 

The last one is what I'm after... but I wont know the tz, so I cant even set it to a variable and pass it in, How do I GET the timezone as a string, not and an offset - OR how can I use the offset to do the same thing? // Sep 8th 15, 10:51 pm CDT

Community
  • 1
  • 1
j-p
  • 3,698
  • 9
  • 50
  • 93

1 Answers1

1

You could use something like jsTimezoneDetect to manually get the IANA time zone designation and append it to the string. However, I don't know how reliable that library is, so this is not an endorsement.

The following is just an example, a robust function requires some validation and error handling for the return value from jstz.determine.

This looks a bit weird, I'm much more used to seeing the actual time zone as +05:30 or whatever.

IANA timezones aren't designed for general use and have the issue of giving a single geographic location to something that actually covers a vast area.

document.write(moment().format('d MMM YYYY HH:mm:ss') + ' ' + jstz.determine().name());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
RobG
  • 142,382
  • 31
  • 172
  • 209