Home > Blockchain >  Convert Only Time to The Relevent Timezone
Convert Only Time to The Relevent Timezone

Time:10-17

I am using moment js to get only the UTC time.

const time = moment().utc().format('HH:mm:ss');

example output is like this - "07:57:49"

I want to change this time value to relevant timezone value.

const americaTime = moment(time).tz("America/Los_Angeles").format();

But there is an warning saying - "Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Is there any alternative way to overcome this issue ?

CodePudding user response:

do this

let time = moment().utc().tz("America/Los_Angeles").format('HH:mm:ss');

CodePudding user response:

moment('07:57:49','HH:mm:ss').tz("America/Los_Angeles").format();

You need to specify the format'HH:mm:ss' in the second param

CodePudding user response:

You can also display the time UTC, or in any IANA timezone with vanilla JS, using Date.toLocaleTimeString():

let dt = new Date();

const timeZones = ['UTC', 'America/Los_Angeles', 'America/New_York'];

console.log('Time zone'.padEnd(20), 'Current time')
for(let timeZone of timeZones) {
    console.log(timeZone.padEnd(20), dt.toLocaleTimeString('en', {  timeZone, hourCycle: 'h24', hour: '2-digit', minute: '2-digit', second: '2-digit' }));
}
   
.as-console-wrapper { max-height: 100% !important; }

  • Related