How to format $.now() with Jquery

2020-03-09 08:55发布

问题:

$.now() gives me the time as miliseconds. I need to show it something like hh:mm:ss

How can I do that in Jquery?

回答1:

function formatTimeOfDay(millisSinceEpoch) {
  var secondsSinceEpoch = (millisSinceEpoch / 1000) | 0;
  var secondsInDay = ((secondsSinceEpoch % 86400) + 86400) % 86400;
  var seconds = secondsInDay % 60;
  var minutes = ((secondsInDay / 60) | 0) % 60;
  var hours = (secondsInDay / 3600) | 0;
  return hours + (minutes < 10 ? ":0" : ":")
      + minutes + (seconds < 10 ? ":0" : ":")
      + seconds;
}


回答2:

I'd suggest just using the Javascript Date object for this purpose.

    var d = new Date();
    var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();

Edit: I just came across the method below, which covers formatting issues such as the one mike-samuel mentioned and is cleaner:

    var time = d.toLocaleTimeString();


回答3:

JSFiddle example here

http://jsfiddle.net/NHhMv/

The jquery now is nothing but

The $.now() method is a shorthand for the number returned by the expression

(new Date).getTime().

from jquery

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

and follow this link

Where can I find documentation on formatting a date in JavaScript?



回答4:

new Date().toString().split(' ')[4]

or

new Date().toString().match(/\d{2}:\d{2}:\d{2}/)[0]

The toString method is basically an alias for toLocaleString in most implementations. This will return the time in the user's timezone as opposed to assuming UTC by using milliseconds if you use getTime (if you use getMilliseconds you should be OK) or toUTCString.



回答5:

I'd suggest date-format jQuery plugin. Like this one or this one (I am using the former)



回答6:

I'm way late to this, but thought i'd just throw this little snippet out there for the masses. This is something I use just to get a quick localized timestamp. It's pretty clean and handy.

function getStamp() {
    var d = new Date();

    var mm = d.getMilliseconds(), hh = d.getHours(),
        MM = d.getMinutes(), ss = d.getSeconds();

    return (hh < 10 ? "0" : "") + hh + (MM < 10 ? ":0" : ":") + MM + (ss < 10 ? ":0" : ":") + ss + ":" + mm;
};


回答7:

jQuery doesn't have date formatting. You can roll your own with the JavaScript Date object, or you can use a library that does it for you. DateJS is one such library, which provides a rich set of formatting, parsing, and manipulation functionality. However, it hasn't been maintained in years. momentjs is under active development.