Javascript Dateformat For Different Timezones
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 sd
Solution 1:
There is a way to format for time zones.
console.log(newDate().toLocaleDateString('en-US', {timeZone: 'America/Denver'}))
// 11/13/2018console.log(newDate().toLocaleTimeString('en-US', {timeZone: 'America/Denver'}))
// 2:30:54 PMconsole.log(newDate().toLocaleTimeString('en-US', {timeZone: 'America/New_York'}))
// 4:31:26 PM
Solution 2:
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
Solution 3:
If you're just passing the raw TZ there's nothing really complicated about adjusting the hours. My example below is of course abbreviated. Yours may get quite long depending on how many patterns you'd handle.
Date.prototype.format = function(format, tzAdjust) {
// adjust timezonethis.setHours(this.getHours()+tzAdjust)
// pad zero helper - return "09" or "12"var two = function(s){ return s+"".length==1 ? "0"+s : s+""; }
// replace patterns with date numbersreturn format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
switch(pattern){
case"d" : returnthis.getDate();
case"dd" : returntwo(this.getDate());
}
});
}
Solution 4:
Don't write your own stuff; just get datejs: http://www.datejs.com/
You can figure out what the timezone offset is set to in the execution environment like this:
var local = new Date();
var utc = Date.UTC(local.getFullYear(), local.getMonth(), local.getDate(), local.getHours(), local.getMinutes(), local.getSeconds(), local.getMilliseconds());
var tz = (utc - local.getTime()) / (60 * 60 * 1000);
Solution 5:
Attempting to (ever so slightly) improve upon mwilcox's suggestion:
Date.prototype.format = function(format, tzAdjust) {
// get/setup a per-date-instance tzDate object storevar tzCache = this.__tzCache = this.__tzCache || (this.__tzCache = {});
// fetch pre-defined date from cache var tzDate = tzCache[tzAdjust];
if ( !tzDate )
{
// on miss - then create a new tzDate and cache it
tzDate = tzCache[tzAdjust] = newDate( this );
// adjust by tzAdjust (assuming it's in minutes // to handle those weird half-hour TZs :)
tzDate.setUTCMinutes( tzDate.getUTCMinutes()+tzAdjust );
}
return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
// replace each format tokens with a value // based on tzDate's corresponding UTC property
});
}
Post a Comment for "Javascript Dateformat For Different Timezones"