Sunday, May 27, 2012

How do you get a timestamp in JavaScript?


How can I get a timestamp in JavaScript?



Something similar to Unix's timestamp, that is, a single number that represents the current time and date. Either as a number or a string.



Source: Tips4all

9 comments:

  1. The following returns the number of milliseconds since the epoch.

    new Date().getTime();

    ReplyDelete
  2. +new Date;


    I like it, because it is small.

    ReplyDelete
  3. JavaScript works with the number of milliseconds since the epoch whereas most other languages work with the seconds. You could work with milliseconds but as soon as you pass a value to say PHP, the PHP native functions will probably fail. So to be sure I always use the seconds, not milliseconds.

    This will give you a Unix timestamp (in seconds):

    var unix = Math.round(+new Date()/1000);


    This will give you the milliseconds since the epoch (not Unix timestamp):

    var milliseconds = new Date().getTime();

    ReplyDelete
  4. var timestamp = Number(new Date()); // current time as number

    ReplyDelete
  5. var $time = Date.now || function() {
    return +new Date;
    };

    $time()

    ReplyDelete
  6. new Date().valueOf()// returns the number of milliseconds since the epoch

    ReplyDelete
  7. time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);

    ReplyDelete
  8. The Date.getTime() can be very used with a little tweak:


    The value returned by the getTime method is the number of milliseconds
    since 1 January 1970 00:00:00 UTC.


    To get the Unix timestamp such as the one returned by PHP time() function, divide this number by 1000, round or floor if necessary:

    (new Date()).getTime() / 1000

    ReplyDelete
  9. var d=new Date();
    var timestamp = new Array(2);
    timestamp[1] = d.getDate();
    timestamp[2] = d.getMonth();
    document.write(timestamp[1]);
    switch (timestamp[2])
    {
    case 0: document.write("Jan");
    break;

    case 1: document.write("Feb");
    break;

    case 2: document.write("Mar");
    break;

    case 3: document.write("Apr");
    break;

    case 4: document.write("May");
    break;

    case 5: document.write("June");
    break;

    case 6: document.write("July");
    break;

    case 7: document.write("Aug");
    break;

    case 8: document.write("Sept");
    break;

    case 9: document.write("Oct");
    break;

    case 10: document.write("Nov");
    break;

    case 11: document.write("Dec");
    break;
    }

    ReplyDelete