Javascript DateFormat for different timezones
- by Elie
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