0

I've set an event listner on an 'li' element which contains a span element that should output the current date.

I have the following lines of code:

var date = new Date();
date.setTime(e.timeStamp);
var showDate = date.toDateString();
$(this).append('<span class="date-clicked">' + showDate + '</span>');

the idea is to use the event objects 'timeStamp' property to obtain the number of milliseconds from Jan 1st 1970 (epoch/unix time) and then using var showDate to get the right date format to display in the span element inside the respective li element.

I'm using firefox btw.

Each time I click an li element its showing me the epoch time 'Thu Jan 01 1970' instead of what i want to see which is 'Thu Feb 13 2020'.

is there a way I can get e.timeStamp to show me the CURRENT Date instead of the epoch/unix date ?

any pointers or tips in the right direction appreciated folks. Thanks.

Manny D
  • 19
  • 5
  • 1
    What is `e.timeStamp`? Since `e.timeStamp` doesn't return anything (likely to be `undefined`), of course setTime will simply set the date to the first timestamp of the unix time. – Terry Feb 13 '20 at 13:50
  • Guess you can create date like this: `var date = new Date(e.timeStamp)`... – Zoran Feb 13 '20 at 13:53
  • the first line of code creates a new Date object and its time is set to the time at which the event was clicked ( second line). The time the event was clicked is then converted into a date that can be read (third line). – Manny D Feb 13 '20 at 14:02
  • Interestingly, I tried your suggestion Terry but it doesn't achieve what I'm gunning for. Observe: var date = new Date(e.timeStamp); console.log(date); var clicked = date.toDateString(); The above still outputs the epoch time when viewed in the console heh – Manny D Feb 13 '20 at 14:04
  • Why don't you just use 'new Date()' instead of 'showDate' like $(this).append('' + new Date() + ''); – Rajat Feb 17 '20 at 13:16
  • If `e.timeStamp` is a Unix timestamp, it's in seconds, and you need to multiply by 1000 before setting the time. If `e.timeStamp` is a JS timestamp, then it should be working. – Heretic Monkey Aug 25 '20 at 18:29

1 Answers1

2

@Manny D, I think we may be working from the same book as the code you posted looks almost identical to the problem I had. This is the code I used to solve the problem, eo is for event object, by the way. I added a forward slash to make it look neater as well...

    $(function() {  
            $("li").on("click", function(eo) {
            
                $("li span").remove();
                var date = new Date();
                date.setTime(eo.timeStamp);                 
                $(this).append("<span class='date'> / " + new Date().toDateString() + "</span>");
            
        
realMecoy
  • 21
  • 2