开发者

Problem in Date calculation in Javascript

I am using the below code to convert a string to a date.

I pass this "2010-06-23 00:00:00.0"开发者_运维知识库 as the input to the function. Instead of returning 21-June-2010 as the date, it returns me 21-Jul-2010. What could be the problem?

function getDateFromString(string){
var month = string.substring(5,7);
var day = string.substring(8,10);
var year = string.substring(0,4);
var dateValue = new Date(year,month,day);
dateFormat(dateValue, "yyyy-mm-dd");
return date;
} 


The months are numbered from zero, not one. In other words, "6" is July, not June.

(I mean, they're numbered that way as far as the JavaScript "Date" class is concerned.)


The month parameter of the Date() object constructor is zero-based.

var dateValue = new Date(year, month - 1, day);


The month has to be the actual month -1. You can find some examples at Date - MDC Docs in the section "Example: Several ways to assign dates" for example.

Edit: Changed link to MDC Docs after Bernhard Hofmann's suggestion.


You are using substring which takes from and to as params. so basically you're always getting 3 characters with substring. (year even 5 chars)

var month = parseInt(string.substr(5,2));
var day = parseInt(string.substr(8,2));
var year = parseInt(string.substr(0,4));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜