Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Date() function returns December 31, 1969 instead of current date

I'm learning jQuery from the Jon Duckett book "Javascript & jQuery: Interactive Front-End Development". So far all the code I've copied from the book seems to be running smoothly, however this code has me stumped. Basically what happens is when you click on a list item in the HTML it displays the date the click event occurred next to the li. It works, but the date displays December 31, 1969 instead of the object clicked date. I've been reading up on how to fix this, but I've had no luck. Is there a different way to get this same result, or am I just missing something in the code?

The jQuery snippet and jsfiddle link are below: jsFiddle

$(function(){
   $('li').on('click', function(e){
    $('li span').remove();
    var date = new Date();
    date.setTime(e.timeStamp);
    var clicked = date.toDateString();
    $(this).append('<span class="date">' + clicked + ' ' + e.type + '</span>');
  });
});
like image 820
photogcoder Avatar asked Jan 03 '23 06:01

photogcoder


1 Answers

That is because e.timeStamp returns DOMHighResTimeStamp and not DOMTimeStamp. Which is very less. Due to which it sets the date as default to 12/31/1969.

new Date(), creates a new date object with the current date and time. You don't need to setTime explicitly here:

var date = new Date();
var clicked = date.toDateString();
like image 112
Milind Anantwar Avatar answered Jan 13 '23 19:01

Milind Anantwar