将纪元时间转换为指定时区的人类可读格式

9

要将纪元日期时间转换为人类可读格式,只需使用简单的new date(1495159447834)即可。

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

因此,如何将纪元数字转换为特定的给定时区以人类可读的格式。

我尝试过像这样的示例:

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

当我尝试将日期字符串转换为日期时,它返回“Invalid Date”。

如果可能的话,我希望不使用任何库。我已经查看了这里的答案,但我相信我没有找到我要找的答案。如果有以前回答过相同主题的问题,请告诉我,我会关闭此问题!


“我希望他/她能够遵循服务器的时区” - 这样会不会让用户感到困惑呢? - nnnnnn
@nnnnnn的原因是,如果按照本地设备时区来设置日期时间,用户可以“欺骗”它。由于我正在开发的应用程序涉及到时间敏感数据,因此按照服务器时区来设置更为可行。 - Gene
4个回答

15

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

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

偏移量将是您所在的特定时区。例如:格林威治标准时间+03:00,您的偏移量为+3。如果是GMT-10:00,则偏移量为-10。


5

有多种方法可以在Epoch和人类可读格式之间进行转换

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

//这将返回2018年8月1日星期三14:11:07 GMT

  //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

Edit# 在此处添加了JSFiddle 链接


如果在 TypeScript / Angular 5/6 中抛出错误,则可以使用 toUTCString()。 - GuyFromChennai

1

这个是旧的,但我是这么做的:

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 GMT-3,但是使用这个代码,它将被显示为洛杉矶应该显示的时间。我的要求是,在我从阿根廷访问页面时,显示洛杉矶时区的时间。

0

将初始日期设置为时代并添加UTC单位。假设您有以秒为单位存储的UTC时代变量。如何将其转换为本地时区的正确日期:

var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to 
the epoch
d.setUTCSeconds(utcSeconds);

或者您可以使用momentjs

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

或者你可以使用这种方式

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()
);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接