将纪元时间转换为具有特定时区的人类可读时间

时间:2017-05-19 03:13:17

标签: javascript datetime epoch

要将epoch dateTime转换为人类可读,使用简单的new date(1495159447834)就足够了。

我现在遇到的问题是,对于我的混合应用程序,如果用户将手机日期时间设置中的时区设置为GMT +12:00,那么人类可读的dateTime将与我希望用户拥有什么,我希望他/她遵循服务器时区。

因此,我如何将人物可读格式的纪元号转换为特定的给定时区。

我试过像:

var test= new Date('1495159447834 GMT+0800').toString();

它会返回一个无效日期。

如果可能的话,我希望没有任何库。我在这里查看了答案,我相信我找不到任何我想要的答案。如果以前回答过相同主题的问题,请告诉我,我将结束这个问题!

4 个答案:

答案 0 :(得分:4)

您可以使用偏移将当前日期时间转换为特定时区。

function convertEpochToSpecificTimezone(offset){
    var d = new Date(1495159447834);
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);  //This converts to UTC 00:00
    var nd = new Date(utc + (3600000*offset));
    return nd.toLocaleString();
}

偏移量将是您的特定时区。示例:GMT +03:00,您的偏移量为+3。如果GMT -10:00,则偏移为-10

答案 1 :(得分:1)

有很多方法可以在时代和人类可读格式之间进行转换

//Convert epoch to human readable date
var myDate = new Date( 1533132667*1000);
document.write(myDate.toGMTString()+"<hr>"+myDate.toLocaleString());

///这将返回2018年8月1日星期三格林尼治标准时间

  //Convert human readable dates to epoch
var myDate = new Date("Wed Aug 01 2018 14:11:07 GMT"); 
var myEpoch = myDate.getTime()/1000.0;

//这将返回1533132667

供参考:https://www.epochconverter.com/programming/#javascript

编辑# 添加了JSFiddle here

答案 2 :(得分:0)

这是旧的,但我是这样做的:

function formatDate(date, includeTime) {
  const dateTimeFormat = new Intl.DateTimeFormat('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    timeZone: 'America/Los_Angeles',
    timeZoneName: 'short',
  });
  const [
    { value: month },
    ,
    { value: day },
    ,
    { value: year },
    ,
    { value: hour },
    ,
    { value: minute },
    ,
    { value: dayPeriod },
    ,
    { value: timeZoneName },
  ] = dateTimeFormat.formatToParts(date);
  if (includeTime) {
    return `${day} ${month} ${year} • ${hour}:${minute}${dayPeriod.toLowerCase()} ${timeZoneName}`;
  }
  return `${day} ${month} ${year}`;

这将输出给定时区的时间。

例如,如果我有一个纪元时间(unix时间戳),并且我在阿根廷,则该时间应显示为6月2日格林尼治标准时间03:45 -3,但是使用此代码,它将显示为洛杉矶应该显示的时间。 我的要求是即使我从阿根廷访问该页面,也要显示洛杉矶时区的时间。

答案 3 :(得分:-1)

将初始日期设置为纪元并添加UTC单位。假设您有一个UTC纪元var存储在几秒钟内。 1234567890怎么样。要将其转换为当地时区的正确日期:

moment.unix(yourUnixEpochTime).format('dddd, MMMM Do, YYYY h:mm:ss A')

或者你可以使用momentjs

var dateVal ="/Date(1342709595000)/";
var date = new Date(parseFloat(dateVal.substr(6)));
document.write( 
    (date.getMonth() + 1) + "/" +
    date.getDate() + "/" +
    date.getFullYear() + " " +
    date.getHours() + ":" +
    date.getMinutes() + ":" +
    date.getSeconds()
);

或者你可以这样使用

&#13;
&#13;
sendMessage
&#13;
&#13;
&#13;

相关问题