Javascript DateFormat for different timezones

Posted by Elie on Stack Overflow See other posts from Stack Overflow or by Elie
Published on 2010-04-10T13:21:26Z Indexed on 2010/04/10 13:23 UTC
Read the original article Hit count: 532

Filed under:

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

© Stack Overflow or respective owner

Related posts about JavaScript