Robin Alexander
Robin Alexander

Reputation: 1004

Display local timezone name with moment.js

I am using moment.js and would like to show the user's local timezone name like CET or PST using

var timezone_local = moment.tz().zoneName(); 
document.getElementById('timezone_local').innerHTML = timezone_local;

Those lines do not work. Thanks for your help!

Upvotes: 25

Views: 56497

Answers (5)

SNag
SNag

Reputation: 18141

.format("z") with a lowercase z prints out just the timezone abbreviation.

Here are a few examples:

let currentTime = moment().tz(moment.tz.guess());
console.log(currentTime.format("z")); // PST

let parisTime = moment().tz("Europe/Paris");
console.log(parisTime.format("z")); // CET

let indiaTime = moment().tz("Asia/Kolkata");
console.log(indiaTime.format("z")); // IST

let newYorkTime = moment().tz("America/New_York");
console.log(newYorkTime.format("z")); // EST

let newYorkTimeDuringDST = moment("2020-08-01").tz("America/New_York");
console.log(newYorkTimeDuringDST.format("z")); // EDT

Upvotes: 1

Wahdat Jan
Wahdat Jan

Reputation: 4156

var timeZone = moment.tz.guess();
const zoneName = moment.tz(timeZone).zoneName();
return moment().tz("America/New_York").zoneName();

Upvotes: 0

Rami Alloush
Rami Alloush

Reputation: 2626

I'm just doing this. The z in the format adds the proper abbreviation for the timezone.

 moment().tz('America/New_York').format('MMMM Do YYYY, h:mm a z');

Upvotes: 1

Mahesh Yadav
Mahesh Yadav

Reputation: 2684

Include moment.js and moment-timezone-with-data.js javascript library.

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.11/moment-timezone-with-data.js"></script>

Then use the below code to get the browser timezone name.

<script>
var timezone = moment.tz.guess();
console.log(timezone);
</script>

See the timezone name in the browser console.

Upvotes: -1

user3775217
user3775217

Reputation: 4803

According to the official moment document, you can use moment-timezone

moment.tz.guess();

For further formatting, refer to this.

Edited :

var zone_name =  moment.tz.guess();
var timezone = moment.tz(zone_name).zoneAbbr() 
console.log(timezone);

Refer to this working fiddle.

Upvotes: 39

Related Questions