Dealing With DateTime Format For International Application
Solution 1:
Outputting as an ISO string is the right way to go.
It will probably benefit you to use the JavaScript Date
's toISOString
. As not every browser supports it, you will want to supply it for browsers that do not:
if ( !Date.prototype.toISOString ) {
( function() {
function pad(number) {
var r = String(number);
if ( r.length === 1 ) {
r = '0' + r;
}
return r;
}
Date.prototype.toISOString = function() {
return this.getUTCFullYear()
+ '-' + pad( this.getUTCMonth() + 1 )
+ '-' + pad( this.getUTCDate() )
+ 'T' + pad( this.getUTCHours() )
+ ':' + pad( this.getUTCMinutes() )
+ ':' + pad( this.getUTCSeconds() )
+ '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
+ 'Z';
};
}() );
}
That is taken directly from MDN toISOString. I use it, and I hope that most others are too.
Note the Z
stands for Zulu time (GMT). You can just use midnight (T00:00:00.000Z
) to denote no time. Personally, I tend not to care about the milliseconds portion for what I do and I omit it (time resolution is fine down to the second).
As long as you standardize on the ISO format, then you can easily write simple parsers for both the server and client, if necessary.
As for the DateTime
binding in MVC, you should then parse the incoming value using the methods described in this answer. The key to date/time parsing is consistency, and as long as you can depend on the ISO format (either with the T
or using a space), then you can easily manage it.
Solution 2:
dateFormat(new Date(), 'Y-m-dTH:i:s.uZ'); // Returns 2013-06-07T04:22:26.755
https://gist.github.com/poying/5942293
var dateFormat = (function () {
var keywords = {
Y: 'getFullYear',
m: 'getUTCMonth',
d: 'getUTCDate',
H: 'getUTCHours',
i: 'getUTCMinutes',
s: 'getUTCSeconds',
u: 'getUTCMilliseconds'
};
function pad(number) {
var r = String(number);
if ( r.length === 1 ) {
r = '0' + r;
}
return r;
}
return function dateFormat(date, format) {
var str = '';
var i, len = format.length;
for (i = 0; i < len; i += 1) {
if (keywords.hasOwnProperty(format[i])) {
str += pad(Date.prototype[keywords[format[i]]].call(date));
} else {
str += format[i];
}
}
return str;
}
})();
Post a Comment for "Dealing With DateTime Format For International Application"