我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?

例如,HH/MM/SS格式。


当前回答

// Format value as two digits 0 => 00, 1 => 01
function twoDigits(value) {
   if(value < 10) {
    return '0' + value;
   }
   return value;
}

var date = new Date(unix_timestamp*1000);
// display in format HH:MM:SS
var formattedTime = twoDigits(date.getHours()) 
      + ':' + twoDigits(date.getMinutes()) 
      + ':' + twoDigits(date.getSeconds());

其他回答

moment.js

将时间戳转换为js中的日期字符串

https://momentjs.com/

moment().format('YYYY-MM-DD hh:mm:ss');
// "2020-01-10 11:55:43"

moment(1578478211000).format('YYYY-MM-DD hh:mm:ss');
// "2020-01-08 06:10:11"


不需要40 KB库的现代解决方案:

Intl.DateTimeFormat是格式化日期/时间的非文化帝国主义方式。

// Setup once
var options = {
    //weekday: 'long',
    //month: 'short',
    //year: 'numeric',
    //day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
},
intlDate = new Intl.DateTimeFormat( undefined, options );

// Reusable formatter
var timeStamp = 1412743273;
console.log( intlDate.format( new Date( 1000 * timeStamp ) ) );

这适用于PHP时间戳

变量d=1541415288860;//var d=值时间戳;//注意:变量名前使用+var date=新日期(+d);console.log(d);console.log(date.toDateString());console.log(date.getFullYear());console.log(date.getMinutes());console.log(date.getSeconds());console.log(date.getHours());console.log(date.toLocaleTimeString());

var d =val.timestamp;
var date=new Date(+d); //NB: use + before variable name

console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());

上述方法将生成此结果

1541415288860
Mon Nov 05 2018 
2018 
54 
48 
13
1:54:48 PM

有很多方法可以完美地使用时间戳。无法全部列出

我想使用一个像momentjs.com这样的库,这样做非常简单:

基于Unix时间戳:

var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );

基于MySQL日期字符串:

var now = moment("2010-10-10 12:03:15");
console.log( now.format("HH/mm/ss") );
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