Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中将Unix时间戳转换为时间_Javascript_Date_Time_Time Format - Fatal编程技术网

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

在JavaScript中将Unix时间戳转换为时间,javascript,date,time,time-format,Javascript,Date,Time,Time Format,我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送到一些JavaScript代码中。我怎样才能挤出时间呢 例如,以HH/MM/SS格式。 让unix_timestamp=1549312452 //基于时间戳创建新的JavaScript日期对象 //乘以1000,使参数以毫秒为单位,而不是以秒为单位。 var date=新日期(unix_时间戳*1000); //时间戳中的小时数部分 var hours=date.getHours(); //时间戳中的分钟部分 var minutes=

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

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

让unix_timestamp=1549312452
//基于时间戳创建新的JavaScript日期对象
//乘以1000,使参数以毫秒为单位,而不是以秒为单位。
var date=新日期(unix_时间戳*1000);
//时间戳中的小时数部分
var hours=date.getHours();
//时间戳中的分钟部分
var minutes=“0”+date.getMinutes();
//时间戳的秒数部分
var seconds=“0”+date.getSeconds();
//将以10:30:23格式显示时间
var formattedTime=hours+':'+分钟.substr(-2)+':'+秒.substr(-2);

console.log(格式化时间)JavaScript以毫秒为单位工作,因此首先必须将UNIX时间戳从秒转换为毫秒

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...

UNIX时间戳是自1970年1月1日UTC 00:00:00以来的秒数(根据)

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

例如,请参见下面的代码:

    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);
函数时间转换器(UNIX\u时间戳){
var a=新日期(UNIX_时间戳*1000);
变量月份=['1月'、'2月'、'3月'、'4月'、'5月'、'6月'、'7月'、'8月'、'9月'、'10月'、'11月'、'12月'];
var year=a.getFullYear();
var月=月[a.getMonth()];
var date=a.getDate();
var hour=a.getHours();
var min=a.getMinutes();
var sec=a.getSeconds();
变量时间=日期+月+年+小时+:'+分钟+:'+秒;
返回时间;
}

console.log(时间转换器(0))上述解决方案的问题是,如果小时、分钟或秒只有一个数字(即0-9),则时间可能是错误的,例如,时间可能是2:3:9,但应该是02:03:09

据介绍,使用Date的“toLocaleTimeString”方法似乎是更好的解决方案。

请参阅

您需要
ParseInt
,否则它将无法工作:


if(!window.a)
window.a=新日期();
var mEpoch=parseInt(UNIX_时间戳);
如果(mEpoch<1000000000)
mEpoch*=1000;
------
a、 设定时间(mEpoch);
var year=a.getFullYear();
...
返回时间;
另一种方式-从日期开始

var时间戳=1293683278;
var日期=新日期(时间戳*1000);
var iso=date.toISOString().match(/(\d{2}:\d{2}:\d{2})/)
警报(iso[1])
//将值格式化为两位数字0=>00,1=>01
函数两位数(值){
如果(值<10){
返回“0”+值;
}
返回值;
}
var date=新日期(unix_时间戳*1000);
//以HH:MM:SS格式显示
var formattedTime=两位数(date.getHours())
+“:”+两位数(date.getMinutes())
+“:”+两位数(date.getSeconds());

我偏爱Jacob Wright的库,它以PHP函数的风格实现JavaScript日期格式

new Date(unix_timestamp * 1000).format('h:i:s')

我会考虑使用一个库,比如,这样做非常简单:

基于Unix时间戳:

var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );
const dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");
基于MySQL日期字符串:

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

如果要将Unix持续时间转换为实际小时、分钟和秒,可以使用以下代码:

var hours = Math.floor(timestamp / 60 / 60);
var minutes = Math.floor((timestamp - hours * 60 * 60) / 60);
var seconds = Math.floor(timestamp - hours * 60 * 60 - minutes * 60 );
var duration = hours + ':' + minutes + ':' + seconds;

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

是一种非文化帝国主义的日期/时间格式

// 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 ) ) );
使用,您可以获得如下所示的时间和日期:

var dateTimeString = moment(1439198499).format("DD-MM-YYYY HH:mm:ss");
使用此选项,您只能获得时间:

var timeString = moment(1439198499).format("HH:mm:ss");

注意一些答案的零问题。例如,时间戳
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);
现在的结果是:

12/08/2015 00:49
现代解决方案(2020年) 在新的世界中,我们应该转向标准JavaScript对象,它有一个方便的构造函数和方法:

函数格式\u时间{
const dtFormat=新的Intl.DateTimeFormat('en-GB'{
时间类型:“中等”,
时区:“UTC”
});
返回dtFormat.format(新日期(s*1e3));
}

console.log(格式_time(12345));//“03:25:45”
此时您必须使用unix时间戳:

var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );
const dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");

根据@shomrat的回答,这里有一个自动写入日期时间的片段,如下所示(有点类似于StackOverflow的回答日期:
于2016年11月6日11:51回答了
):

或(如果与今天不同但同一年)

或者(如果比今天多一年)



您可以使用以下功能将时间戳转换为
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 : ':' );
}
如果要使用
/
作为分隔符,只需将其作为第二个参数传递:

time = convertTime(920535115, '/'); // --> OUTPUT = 09/11/55

演示
var convertTime=函数(时间戳、分隔符){
var pad=函数(输入){返回输入<10?“0”+输入:输入;};
var date=时间戳?新日期(时间戳*1000):新日期();
返回[
pad(date.getHours()),
pad(date.getMinutes()),
pad(date.getSeconds())
].join(分隔符的类型!=“未定义”?分隔符:“:”);
}
document.body.innerHTML=''+JSON.stringify({
var s = new Date(1504095567183).toLocaleDateString("en-US")
console.log(s)
// expected output "8/30/2017"  
920535115:convertTime(920535115,“/”), 1061351153:convertTime(1061351153,':'), 1435651350:convertTime(1435651350,“-”), 1487938926:convertTime(1487938926), 1555135551:convertTime(1555135551,“.”) },空,'\t')+'' 函数getDateTimeFromTimestamp(UnixtTimeStamp){ 出租日期=新日期(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);//输出2000年5月1日11:00
使用:

至于时间:

var s=新日期(1504095567183)。toLocaleTimeString(“美国”)
控制台日志
//预期输出“下午3:19:27
const dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");
today, 11:23
yersterday, 11:23
6 Nov, 11:23
6 Nov 2016, 11:23
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;
}
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 : ':' );
}
time = convertTime(1061351153); // --> OUTPUT = 05:45:53
time = convertTime(920535115, '/'); // --> OUTPUT = 09/11/55
var s = new Date(1504095567183).toLocaleDateString("en-US")
console.log(s)
// expected output "8/30/2017"  
(new Date(ts*1000)+'').slice(16,24)