开发者

How split this into new Date

I am grabbing a node from XML that returns the date li开发者_开发问答ke this :

2011-06-24T03:00:00

If I try to run new Date I am getting a NaN error.

 var shippedDate = new Date($j(this).find("Shipment").find("Date").text())

 $j("#result").append(shippedDate.getDate() + "/" + shippedDate.getMonth() + "/" + shippedDate.getFullYear() );

I am thinking I need to use a regular expression to grab everything before the T and drop the rest then it will work ?

Can someone please show me what that regex would look like or if there is another solution?


I think there might be an issue with how you are calling $j(this) because when I strip it all out, it works:

var shippedDate = new Date("2011-06-24T03:00:00");

 $("#result").append(shippedDate.getDate() + "/" + shippedDate.getMonth() + "/" + shippedDate.getFullYear() );

http://jsfiddle.net/jasongennaro/Ry9u8/


It works just fine for me

var somedate = new Date('2011-06-24T03:00:00');

// Fri Jun 24 2011 03:00:00 GMT+0300 (GTB Daylight Time)

demo at http://jsfiddle.net/gaby/8Xwbj/2/

Are you sure the $j(this).find("Shipment").find("Date").text() returns what you expect it to ?


You should use Date.parse() to get the date from an string :) https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse


This would work:

"2011-06-24T03:00:00".match(/(\d{4}-\d{2}-\d{2})/)[0]


The dateString must follow RFC 1123 timestamps or since JavaScript 1.8.5 subset of ISO 8601 date strings so it could be picked up by the parse method.

From Mozilla JavaScript reference:

new Date(milliseconds)
new Date(dateString)

dateString String value representing a date. The string should be in a format recognized by the parse method (IETF-compliant RFC 1123 timestamps).

milliseconds Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC.


Try using the indexOf method of javascript's String object in combination with the substr method, i.e.:

$string.substr(0, $string.indexOf('T'));

I'm more a java/perl coder than a javascript coder, so my syntax might be slightly off, but I hope you get the idea.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜