开发者

Javascript: date conversion

How can I write the Dateformat for "2010-12-07 17:53:17.0_getCreated_10开发者_JAVA技巧032" in Javascript so that sorting can be done accordingly?

Thanks in advance,

Joseph


not sure what that stuff ont he end is - up to the getCreated bit it looks like a MySQL datetime field.

first, get rid of that:

var str = "2010-12-07 17:53:17.0_getCreated_10032";
str = str.replace(/(\d{2}:\d{2}:\d{2}).*$/g, '$1');  // now is 2010-12-07 17:53:17

then you need to move the year so it reads M-D-Y...

str = str.replace(/^(\d{4})-(\d{2})-(\d{2})/g, '$2-$3-$1');

now it's a valid date string so you can feed it to the Date constructor...

var date = new Date(str);

and to sort it, cast it as a number

var num = Number(date);

so alltogehter it looks like this:

var str = "2010-12-07 17:53:17.0_getCreated_10032";
str = str.replace(/(\d{2}:\d{2}:\d{2}).*$/g, '$1');
str = str.replace(/^(\d{4})-(\d{2})-(\d{2})/g, '$2-$3-$1');
var date = new Date(str);
var num = Number(date);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜