-2

I want to assign date to new date object. when I am using it is not giving correct result http://jsfiddle.net/Cqw5c/

new Date (12/12/2012)
Jitender
  • 7,593
  • 30
  • 104
  • 210
  • I have date in var like var mydate= 12/12/2012. How to pass mydate as string as date object i am using d= new date(mydate) – Jitender Oct 18 '13 at 13:42

3 Answers3

1
function getD() {
var d = new Date("12/12/2012");
var month = d.getMonth()+1;
var day   = d.getDate();
var year  = d.getFullYear();

alert( month + "/" + day + "/" + year);
                }

Update

HTML:

$('#clickme').click(function() {
  var thetestdate = $('#testdate').val();
  mynewdate = getD(thetestdate);
  alert(mynewdate);
});

JS:

function getD(mydatevariable) {
var d = new Date(mydatevariable);
var month = d.getMonth()+1;
var day   = d.getDate();
var year  = d.getFullYear();
var wholedate = ( month + "-" + day + "-" + year);
return wholedate;
                               }
TimSPQR
  • 2,964
  • 3
  • 20
  • 29
0

Quote the argument:

var d= new Date("12/12/2012");

Here's an updated fiddle. You're currently creating a date with the result of the expression 12/12/2012, which is three numbers and two division operators:

console.log(12 / 12 / 2012); // 0.0004970178926441351
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • 1
    Please stop answering duplicates instead of marking them ;) – plalx Oct 18 '13 at 13:32
  • @plalx - I find it quicker and more helpful to the OP to answer the question when it's such a simple one. If a duplicate then appears I always vote to close as well. – James Allardice Oct 18 '13 at 13:33
  • Perhaps it's faster but it pollutes SO and doesn't condition people to search before asking. (I did not downvote btw) – plalx Oct 18 '13 at 13:35
  • @plalx - I don't think it pollutes SO since the question will get closed as a dupe anyway. True about conditioning people to search before asking though. Here is not the place for this discussion though, I think it's been brought up on meta several times (where your approach does tend to be the accepted one I admit). – James Allardice Oct 18 '13 at 13:36
  • @plalx - Also, just closing as a dupe doesn't explain to the OP what's going wrong in their particular case. – James Allardice Oct 18 '13 at 13:38
  • 1
    You can always post a comment. I guess there could be cases where the question is complex enough to answer it even if it seems to be a possible duplicate, however it shouldn't be the norm. – plalx Oct 18 '13 at 13:40
0

You're creating a new date based on

(12 / 12) / 2012 == 0.0004970178926441351

which will be some fraction of a second after January 1, 1970.

You can create a Javascript date by parsing a string:

new Date( "12/12/2012");

or by passing in individual components:

new Date( 2012, 12, 12 );

See Date at MDN for more variations.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93