Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript DateFormat for different timezones

Tags:

javascript

I'm a Java developer and I'm used to the SimpleDateFormat class that allows me to format any date to any format by settings a timezone.

Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
System.out.println(sdf.format(date)); // Prints date in Los Angeles

sdf.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
System.out.println(sdf.format(date)); // Prints same date in Chicago

SimpleDateFormat is a pretty neat solution in Java but unfortunately I can't find any similar alternative in Javascript.

I'm extending the Date prototype in Javascript to do exactly the same. I have dates in Unix format but I want to format them in different timezones.

Date.prototype.format = function(format, timezone) {
    // Now what?
    return formattedDate;
}

I'm looking for a neat way to do this rather than a hack.

Thanks

like image 683
Elie Avatar asked Apr 10 '10 13:04

Elie


People also ask

How does JavaScript handle different time zones?

The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC.

How do I convert one time zone to another in JavaScript?

You can use to toLocaleString() method for setting the timezone.

Does date now () depend on timezone?

Yes, Date. now() will give you the same UTC timestamp independent of your current timezone. Such a timestamp, rather a point in time, does not depend on timezones. The Java equivalent new Date() gives you the exact same thing.


2 Answers

There is a way to format for time zones.

console.log(new Date().toLocaleDateString('en-US', {timeZone: 'America/Denver'}))
// 11/13/2018
console.log(new Date().toLocaleTimeString('en-US', {timeZone: 'America/Denver'}))
// 2:30:54 PM
console.log(new Date().toLocaleTimeString('en-US', {timeZone: 'America/New_York'}))
// 4:31:26 PM

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString

like image 89
j4ys0n Avatar answered Oct 29 '22 11:10

j4ys0n


The ISO Extended format for common date is YYYY-MM-DD, and for time is hh:mm:ss. Either format can be understood, unambiguously, worldwide.

See also: http://jibbering.com/faq/#dates

like image 21
Garrett Avatar answered Oct 29 '22 13:10

Garrett