Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
58
rated 0 times [  65] [ 7]  / answers: 1 / hits: 17368  / 9 Years ago, wed, december 16, 2015, 12:00:00

I have to display a string on the web page in this format: 16:00 HH:mm



I'm using a moment object to represent a date/time and timezone.



var day = moment().tz('GMT');
day.hours(16).minutes(0).seconds(0).milliseconds(0);


So this is 16:00 in GMT time.



On my web page I want to change the time zone and then collect the hours and minutes.



If I make a new moment object



var day2 = moment().tz('PST); //this is 8 AM since gmt was 16
console.log(day2.get('hours'));


it is 16 not 8!



and try to get the hours and minutes they are in GMT not in PST.



How can I get it in PST? Do I have to keep wrapping it?


More From » timezone

 Answers
4
// initialize a new moment object to midnight UTC of the current UTC day
var m1 = moment.utc().startOf('day');

// set the time you desire, in UTC
m1.hours(16).minutes(0);

// clone the existing moment object to create a new one
var m2 = moment(m1); // OR var m2 = m1.clone(); (both do the same thing)

// set the time zone of the new object
m2.tz('America/Los_Angeles');

// format the output for display
console.log(m2.format('HH:mm'));


Working jsFiddle here.



If you can't get it to work, then you haven't correctly loaded moment, moment-timezone, and the required time zone data. For the data, you either need to call moment.tz.add with the zone data for the zones you care about, or you need to use one of the moment-timezone-with-data files available on the site.



In the fiddle, you can see the moment-files I'm loading by expanding the External Resources section.



fiddle


[#64037] Monday, December 14, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominickmackenziet

Total Points: 583
Total Questions: 101
Total Answers: 117

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
dominickmackenziet questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Fri, Feb 12, 21, 00:00, 3 Years ago
;