0

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;
} 
2
  • 3
    Dates are 0-based. So 06 is actually the 7th month of the year. Commented Jun 16, 2011 at 21:25
  • basically what everyone has responded with =) Commented Jun 16, 2011 at 21:28

4 Answers 4

3

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.)

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

1

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.

1 Comment

Oh Dan - now what do I do? +1 for month offset, but -1 for referencing w3cSchool :p Please use MDC Docs: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.