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

rof*_*fle 1054 javascript time date date-format time-format

我将时间存储在MySQL数据库中作为Unix时间戳,并将其发送到某些JavaScript代码.我怎么才能得到它的时间?

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

Aro*_*eel 1584

// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();

// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
Run Code Online (Sandbox Code Playgroud)

有关Date对象的更多信息,请参阅MDNECMAScript 5规范.

  • @nickf乘法在现代CPU上是微不足道的 - 字符串连接需要_lot_更多的工作! (108认同)
  • 实际上它将以'10:2:2'格式显示时间,因为它不会在低于10的值之前添加额外的0. (29认同)
  • @ user656925 - 乘法涉及数字,连接涉及字符串.计算机处理数字远比字符串更有效.当字符串连接完成时,后台会进行大量的内存管理.(但是,如果您已经在进行字符串连接,那么在其中一个字符串中包含一些额外的字符实际上可能实际上比一个处理器op成本更低,将两个数字相乘.) (14认同)
  • @Stallman数字计算是计算机最基本的事情,它们在内存和运行时都非常高效.Brilliand上面的评论是相关的,尽管恕我直言,他评论的最后部分完全是假的. (5认同)
  • 连接应该包括阅读记忆和写记忆.如果有人设计出一些简单的东西,如追加,并使其比多项更复杂...要求孩子连接,他们可以..多重化更难...加上记忆以便线性地工作任何人...有人可以提供对@nickf评论的引用吗? (4认同)
  • @Stallman所有语言都是如此(或者几乎所有语言都是理论上可以创建一种不像这样的外来语言 - 但所有常见语言都是如此).字符串在内部存储为指向存储字符串内容的内存块的指针.指针本身使用与大多数数字在同一系统上相同的内存量,并且存储实际字符串的内存除此之外.然后,当您连接字符串时,您最常创建一个全新的字符串,其中包含两个字符串的组合内容. (2认同)

小智 277

function timeConverter(UNIX_timestamp){
  var a = new Date(UNIX_timestamp * 1000);
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var year = a.getFullYear();
  var month = months[a.getMonth()];
  var date = a.getDate();
  var hour = a.getHours();
  var min = a.getMinutes();
  var sec = a.getSeconds();
  var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
  return time;
}
console.log(timeConverter(0));
Run Code Online (Sandbox Code Playgroud)

  • 我使用了这个解决方案,但调整了它,以便分钟和秒显示为:03或:09而不是:3或:9,就像这样:`var min = a.getMinutes()<10?'0'+ a.getMinutes():a.getMinutes(); var sec = a.getSeconds()<10?'0'+ a.getSeconds():a.getSeconds();` (34认同)
  • 错误:`getMonth()`返回0到11之间的月份数,因此`a.getMonth() - 1`是错误的. (3认同)

Ste*_*son 179

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

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...
Run Code Online (Sandbox Code Playgroud)


Bra*_*och 76

我偏爱Jacob Wright的Date.format()库,它以PHP的date()功能风格实现JavaScript日期格式化.

new Date(unix_timestamp * 1000).format('h:i:s')
Run Code Online (Sandbox Code Playgroud)

  • 我知道这是很好的回答,但是现在扩展原生js对象是一种反模式. (10认同)
  • 它在节点 js 中不起作用(不再?)`格式不是函数`。但这显然有效:/sf/answers/2381085801/ (4认同)

Vis*_*ioN 52

以下是将秒格式化为最短的单行解决方案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"
Run Code Online (Sandbox Code Playgroud)

方法Date.prototype.toISOString()以简化的扩展ISO 8601格式返回时间,该格式总是 24或27个字符长(即YYYY-MM-DDTHH:mm:ss.sssZ±YYYYYY-MM-DDTHH:mm:ss.sssZ分别).时区始终为零UTC偏移.

注意:此解决方案不需要任何第三方库,并且在所有现代浏览器和JavaScript引擎中都受支持.


Dan*_*anu 46

使用:

var s = new Date(1504095567183).toLocaleDateString("en-US")
// expected output "8/30/2017"   
Run Code Online (Sandbox Code Playgroud)

并且时间:

var s = new Date(1504095567183).toLocaleTimeString("en-US") 
// expected output "3:19:27 PM"`
Run Code Online (Sandbox Code Playgroud)

请参阅Date.prototype.toLocaleDateString()

  • 请注意,数字“1504095567183”是 unix_timestamp * 1000 (6认同)
  • 此外,“toLocaleString”包括日期和时间。 (3认同)

hom*_*mtg 28

我想考虑使用像momentjs.com这样的库,这让这很简单:

基于Unix时间戳:

var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );
Run Code Online (Sandbox Code Playgroud)

基于MySQL日期字符串:

var now = moment("2010-10-10 12:03:15");
console.log( now.format("HH/mm/ss") );
Run Code Online (Sandbox Code Playgroud)

  • 对于像"6小时前"这样的消息,moment.js(或类似的库)的另一个优点是他们对[相对时间](http://momentjs.com/docs/#/customization/relative-time/)的支持. (2认同)

Grz*_*lik 21

UNIX时间戳的数(根据在1970年1月1日以来00:00:00 UTC 维基百科).

Javascript中Date对象的参数是自1970年1月1日00:00:00 UTC以来的毫秒数(根据W3Schools Javascript文档).

请参阅以下代码,例如:

    function tm(unix_tm) {
        var dt = new Date(unix_tm*1000);
        document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');

    }

tm(60);
tm(86400);
Run Code Online (Sandbox Code Playgroud)

得到:

1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)
Run Code Online (Sandbox Code Playgroud)


Pet*_* T. 17

使用Moment.js,你可以得到这样的时间和日期:

var dateTimeString = moment(1439198499).format("DD-MM-YYYY HH:mm:ss");
Run Code Online (Sandbox Code Playgroud)

你只能花时间使用它:

var timeString = moment(1439198499).format("HH:mm:ss");
Run Code Online (Sandbox Code Playgroud)


Lui*_*vid 16

将秒格式为hh:mm:ss:变体的最短的一线解决方案:

console.log(new Date(1549312452 * 1000).toISOString().slice(0, 19).replace('T', ' '));
// "2019-02-04 20:34:12"
Run Code Online (Sandbox Code Playgroud)

  • @keanu_reeves - 听起来你在美国东部时区,时间戳是 UTC。尝试删除 .slice(0,19),我想您会看到结果的时区是 Z (祖鲁语)。 (2认同)

小智 15

上述解决方案的问题在于,如果小时,分钟或秒,只有一位数(即0-9),则时间错误,例如可能是2:3:9,但它应该是02: 03:09.

根据这个页面,使用Date的"toLocaleTimeString"方法似乎是一个更好的解决方案.

  • 对于大多数Web解决方案,这是最正确的答案,因为它使用客户端的语言环境,例如24h与12h am/pm格式.对于时间字符串,您将使用:`date.toLocaleTimeString()` (5认同)

dea*_*unk 13

另一种方式 - 从ISO 8601日期开始.

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


Val*_*x85 13

您必须使用unix时间戳:

var dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");
Run Code Online (Sandbox Code Playgroud)


Bas*_*asj 10

根据@ shomrat的回答,这里有一个自动写入日期时间的片段(有点类似于StackOverflow的答案日期:) answered Nov 6 '16 at 11:51:

today, 11:23
Run Code Online (Sandbox Code Playgroud)

要么

yersterday, 11:23
Run Code Online (Sandbox Code Playgroud)

或(如果不同但与今天相同)

6 Nov, 11:23
Run Code Online (Sandbox Code Playgroud)

或(如果是今天的另一年)

6 Nov 2016, 11:23
Run Code Online (Sandbox Code Playgroud)
function timeConverter(t) {     
    var a = new Date(t * 1000);
    var today = new Date();
    var yesterday = new Date(Date.now() - 86400000);
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var year = a.getFullYear();
    var month = months[a.getMonth()];
    var date = a.getDate();
    var hour = a.getHours();
    var min = a.getMinutes();
    if (a.setHours(0,0,0,0) == today.setHours(0,0,0,0))
        return 'today, ' + hour + ':' + min;
    else if (a.setHours(0,0,0,0) == yesterday.setHours(0,0,0,0))
        return 'yesterday, ' + hour + ':' + min;
    else if (year == today.getFullYear())
        return date + ' ' + month + ', ' + hour + ':' + min;
    else
        return date + ' ' + month + ' ' + year + ', ' + hour + ':' + min;
}
Run Code Online (Sandbox Code Playgroud)


Sai*_*ddy 10

有多种方法可以将unix时间戳转换为时间(HH/MM/SS)

  1. 使用new Date()- 这是内置在 javascript 中
  2. moment 包 - 这是一个著名的节点模块,但它将被弃用。
  3. dayjs 包 - 这是最新且快速增长的节点模块之一

使用新的日期()

const dateTimeStr = new Date(1504052527183).toLocaleString()
const result = (dateTimeStr.split(", ")[1]).split(":").join("/")
console.log(result)
Run Code Online (Sandbox Code Playgroud)

使用时刻

const moment = require('moment')
const timestampObj = moment.unix(1504052527183);
const result = timestampObj.format("HH/mm/ss")
console.log(result);
Run Code Online (Sandbox Code Playgroud)

使用day.js

const dayjs = require('dayjs')
const result = dayjs(1504052527183).format("HH/mm/ss")
console.log(result);
Run Code Online (Sandbox Code Playgroud)

您可以使用在线时间转换工具检查时间戳到日期时间的转换


Adr*_*ria 9

不需要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 ) ) );
Run Code Online (Sandbox Code Playgroud)


jam*_*ace 8

我的时间戳是从PHP后端获取的。我尝试了上述所有方法,但没有成功。然后,我遇到了一个有效的教程:

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());
Run Code Online (Sandbox Code Playgroud)

上面的方法将产生此结果

1541415288860
Mon Nov 05 2018 
2018 
54 
48 
13
1:54:48 PM
Run Code Online (Sandbox Code Playgroud)

有很多方法可以与时间戳完美配合。不能全部列出


syn*_*n54 7

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
Run Code Online (Sandbox Code Playgroud)


Tec*_*dom 6

注意一些答案的零问题.例如,时间戳1439329773将被错误地转换为12/08/2015 0:49.

我建议使用以下方法来解决这个问题:

var timestamp = 1439329773; // replace your timestamp
var date = new Date(timestamp * 1000);
var formattedDate = ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
console.log(formattedDate);
Run Code Online (Sandbox Code Playgroud)

现在结果是:

12/08/2015 00:49
Run Code Online (Sandbox Code Playgroud)


Ash*_*pta 6

function getDateTimeFromTimestamp(unixTimeStamp) {
    let date = new Date(unixTimeStamp);
    return ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
}

const myTime = getDateTimeFromTimestamp(1435986900000);
console.log(myTime); // output 01/05/2000 11:00
Run Code Online (Sandbox Code Playgroud)


小智 5

function timeConverter(UNIX_timestamp){
 var a = new Date(UNIX_timestamp*1000);
     var hour = a.getUTCHours();
     var min = a.getUTCMinutes();
     var sec = a.getUTCSeconds();
     var time = hour+':'+min+':'+sec ;
     return time;
 }
Run Code Online (Sandbox Code Playgroud)


小智 5

请参阅日期/纪元转换器

你需要这样做ParseInt,否则它不会工作:


if (!window.a)
    window.a = new Date();

var mEpoch = parseInt(UNIX_timestamp);

if (mEpoch < 10000000000)
    mEpoch *= 1000;

------
a.setTime(mEpoch);
var year = a.getFullYear();
...
return time;
Run Code Online (Sandbox Code Playgroud)


Fir*_*aze 5

// 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());
Run Code Online (Sandbox Code Playgroud)

  • @trejder,在你的例子中,你重复逻辑,而有额外的功能,你在一个地方.你也可以在这里触发日期功能(例如getHours())两次 - 这是一次通话.你永远不会知道某些库函数有多重要被重新执行(但是我相信它对于日期来说很轻松). (2认同)

Joh*_*ers 5

您可以使用以下函数将时间戳转换为HH:MM:SS格式:

var convertTime = function(timestamp, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    var date = timestamp ? new Date(timestamp * 1000) : new Date();
    return [
        pad(date.getHours()),
        pad(date.getMinutes()),
        pad(date.getSeconds())
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}
Run Code Online (Sandbox Code Playgroud)

不传递分隔符,它:用作(默认)分隔符:

time = convertTime(1061351153); // --> OUTPUT = 05:45:53
Run Code Online (Sandbox Code Playgroud)

如果要/用作分隔符,只需将其作为第二个参数传递:

time = convertTime(920535115, '/'); // --> OUTPUT = 09/11/55
Run Code Online (Sandbox Code Playgroud)

演示

var convertTime = function(timestamp, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    var date = timestamp ? new Date(timestamp * 1000) : new Date();
    return [
        pad(date.getHours()),
        pad(date.getMinutes()),
        pad(date.getSeconds())
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}
Run Code Online (Sandbox Code Playgroud)

另请参阅此 Fiddle


Kam*_*ski 5

最短

(new Date(ts*1000)+'').slice(16,24)
Run Code Online (Sandbox Code Playgroud)

(new Date(ts*1000)+'').slice(16,24)
Run Code Online (Sandbox Code Playgroud)


小智 5

尝试这个 :

      new Date(1638525320* 1e3).toISOString()  //2021-12-03T09:55:20.000Z
Run Code Online (Sandbox Code Playgroud)