将Unix时间戳转换为JavaScript中的时间

我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送到一些JavaScript代码。我怎么会得到时间呢?

例如,以HH / MM / SS格式。

猿伽罗2020/03/09 23:50:03
function getTIMESTAMP() {
  var date = new Date();
  var year = date.getFullYear();
  var month = ("0" + (date.getMonth() + 1)).substr(-2);
  var day = ("0" + date.getDate()).substr(-2);
  var hour = ("0" + date.getHours()).substr(-2);
  var minutes = ("0" + date.getMinutes()).substr(-2);
  var seconds = ("0" + date.getSeconds()).substr(-2);

  return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
}

//2016-01-14 02:40:01
A樱2020/03/09 23:50:03

Another way - from an ISO 8601 date.

var timestamp = 1293683278;
var date = new Date(timestamp * 1000);
var iso = date.toISOString().match(/(\d{2}:\d{2}:\d{2})/)
alert(iso[1]);

2020/03/09 23:50:03

In moment you must use unix timestamp:

var dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");
逆天乐2020/03/09 23:50:03

Using Moment.js, you can get time and date like this:

var dateTimeString = moment(1439198499).format("DD-MM-YYYY HH:mm:ss");

And you can get only time using this:

var timeString = moment(1439198499).format("HH:mm:ss");
Tony神乐2020/03/09 23:50:02

Use:

var s = new Date(1504095567183).toLocaleDateString("en-US")
// expected output "8/30/2017"  
console.log(s);

and for time:

var s = new Date(1504095567183).toLocaleTimeString("en-US")
// expected output "3:19:27 PM"
console.log(s)

see Date.prototype.toLocaleDateString()

神离伊芙妮2020/03/09 23:50:02

JavaScript以毫秒为单位工作,因此您首先必须将UNIX时间戳从秒转换为毫秒。

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...
Sam猪猪2020/03/09 23:50:02

Here is the shortest one-liner solution to format seconds as hh:mm:ss:

/**
 * Convert seconds to time string (hh:mm:ss).
 *
 * @param Number s
 *
 * @return String
 */
function time(s) {
    return new Date(s * 1e3).toISOString().slice(-13, -5);
}

console.log( time(12345) );  // "03:25:45"

Method Date.prototype.toISOString() returns time in simplified extended ISO 8601 format, which is always 24 or 27 characters long (i.e. YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ respectively). The timezone is always zero UTC offset.

N.B.: This solution does not require any third-party libraries and is supported in all modern browsers and JavaScript engines.