How to get current time with jQuery

后端 未结 15 876
青春惊慌失措
青春惊慌失措 2020-12-07 08:10

The following returns time in microseconds, for example 4565212462.

alert( $.now() );

How do I convert it to a human readable time format,

15条回答
  •  青春惊慌失措
    2020-12-07 08:46

    jQuery's $.now() is an alias of new Date().getTime(), an internal Javascript function.

    http://api.jquery.com/jquery.now/

    This returns the number of seconds elapsed since 1970, commonly referred to (not necessarily correctly) as Unix Time, Epoch or Timestamp, depending on the circles you fall in. It can be really handy for calculating the difference between dates/times using simple maths. It doesn't have any TimeZone information and is always UTC.

    http://en.wikipedia.org/wiki/Unix_time

    There is no need to use jQuery as other than this alias, it does little else to help with date/time manipulation.

    If you are looking for a quick and dirty way of representing the time in text, the Javascript Date object has a "toString" prototype that will return an ISO formatted Date Time.

    new Date().toString();
    //returns "Thu Apr 30 2015 14:37:36 GMT+0100 (BST)"
    

    More than likely though, you will want to customize your formatting. The Date object has the ability to pull out your relevant details so you can build your own string representation.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    var d = new Date(); //without params it defaults to "now"
    var t = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    //Will return 14:37:36
    

    However, as you have asked for a jQuery solution - it is perhaps likely that you are working with older browsers. If you want to do more specific things - especially interpreting strings into Date objects (useful for API responses), you might want to look at Moment.js.

    http://momentjs.com/

    This will ensure cross browser compatibility and has much improved formatting without having to concatenate lots of strings to together! For example:

    moment().format('hh:mm:ss');
    //Will return 14:37:36
    

提交回复
热议问题