1

I am trying to convert mysql datetime into javascript datetime. having issues. does not return the correct date.

$('#ProjectExtendDeadline').change(function(){
    var oldDate = $('#ProjectOldDeadline').val();
    var t = oldDate.split(/[- :]/);
    var days = $('#ProjectExtendDeadline').val();

    var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
    var date = d.getDate()+" "+d.getMonth()+" "+d.getFullYear();
});

Here is the values I get back. I the date is clearly 3 but shows as 2

3 Answers 3

1

Your code is correct. The getMonth method returns a zero-based month (0 .. 11).


Likewise the Date constructor wants a zero-based month, so your code is correct as the value from the database is 1-based.

var d = new Date(2012,0,3);
document.write(d);

OUTPUT

Tue Jan 03 2012 00:00:00 GMT+0000 (GMT Standard Time) 
Sign up to request clarification or add additional context in comments.

Comments

0

I figured it out. STUPID MISTAKE.

The second parameter t[1]-1 has a -1. had to remove. sorry.

1 Comment

No - the month value in the Date constructor is also zero based (0 == January) so your code is completely correct as it stands. I've edited my answer to demonstrate.
0
  function mysqlTimeStampToDate(timestamp) {
    //function parses mysql datetime string and returns javascript Date object
    //input has to be in this format: 2007-06-05 15:26:02
    var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
    var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
    return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
  }

Source

ps: Oh, I see your confusion :) Yep, month = 2 is March. Just make alert(d) and you will understand.

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.