10 December 2007
This post may be outdated due to it was written on 2007. The links may be broken. The code may be not working anymore. Leave comments if needed.
generally everyone has a browser time zone.
var timezoneOffset = -(new Date().getTimezoneOffset());
like mime is 480.

I want add a simple class="date" to time span, then it will add time zone automatically. (MySQL DateTime format for now. I'll use it in my Foorum)

it's a sample html: http://www.fayland.org/jQuery/dateTimeZone.html

it will convert <span class='date'>2007-11-05 12:20:30</span> to 2007-11-05 20:20:30 in my browser.
$(function() {
// follows are copied from datePicker/date.js
// utility method
var _zeroPad = function(num) {
var s = '0'+num;
return s.substring(s.length-2)
//return ('0'+num).substring(-2); // doesn't work on IE :(
};

$(".date").each(function (i) {
var s = $(this).text();
var f = this.id; //format
if (! f) {
f = 'yyyy-mm-dd hh:ii:ss';
}

var d = new Date(1997, 1, 1, 1, 1, 1);
var iY = f.indexOf('yyyy');
if (iY > -1) {
d.setFullYear(Number(s.substr(iY, 4)));
}
var iM = f.indexOf('mm');
if (iM > -1) {
d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1);
}
d.setDate(Number(s.substr(f.indexOf('dd'), 2)));
d.setHours(Number(s.substr(f.indexOf('hh'), 2)));
d.setMinutes(Number(s.substr(f.indexOf('ii'), 2)));
d.setSeconds(Number(s.substr(f.indexOf('ss'), 2)));

var timezoneOffset = -(new Date().getTimezoneOffset());
d.setMinutes(d.getMinutes() + timezoneOffset);

var t = f
.split('yyyy').join(d.getFullYear())
.split('mm').join(_zeroPad(d.getMonth()+1))
.split('dd').join(_zeroPad(d.getDate()))
.split('hh').join(_zeroPad(d.getHours()))
.split('ii').join(_zeroPad(d.getMinutes()))
.split('ss').join(_zeroPad(d.getSeconds()))
;

$(this).text(t);
} );
});


Enjoy!


blog comments powered by Disqus