简体   繁体   English

如何在JavaScript中将日期时间微格式转换为本地时间?

[英]How can I convert datetime microformat to local time in javascript?

I have a page that is currently using the datetime microformat to display a timestamp, but I have only been showing the human-readable time for my own time zone: 我有一个页面当前正在使用datetime微格式显示时间戳,但是我只是在显示自己时区的人类可读时间:

<abbr class="published" title="2009-01-09T09:16:00-05:00">
Friday, January 9, 2009 at 9:16 am (EST)</abbr>

What I'd like to do is rewrite the innerHTML for the abbr tag to be the same format, but in the user's local timezone. 我想做的是将abbr标签的innerHTML重写为相同的格式,但是要在用户的本地时区中进行。 So for a reader in Seattle, the above should be converted to: 因此,对于西雅图的读者而言,以上内容应转换为:

<abbr class="published" title="2009-01-09T09:16:00-05:00">
Friday, January 9, 2009 at 6:16 am (PST)</abbr>

I've looked at the Javascript Date object , which allows me to get the local timezone offset. 我看过Javascript Date对象 ,它使我能够获取本地时区偏移量。 But I have a few problems: 但是我有一些问题:

  1. I don't see an easy way to create a new Date object from an ISO-8601 timestamp. 我没有从ISO-8601时间戳创建新的Date对象的简便方法。 (I suppose I could parse with substrings or regex if there's no faster way.) (如果没有更快的方法,我想可以用子字符串或正则表达式进行解析。)

  2. I don't see a way to get the named abbreviation for the timezone. 我没有找到获取时区命名缩写的方法。 For example, for a reader in Seattle, I'd want the time to have "(PST)" appended to the end, otherwise it is not clear to that user that the timestamp has been converted (especially if he is a frequent visitor and has become accustomed to the fact that my times are in EST). 例如,对于西雅图的读者,我希望在时间末尾附加“(PST)”,否则该用户不清楚时间戳是否已转换(尤其是如果他是常客和我已经习惯了我的时代在美国东部标准时间(EST)。

Here is code of mine that parses an ISO timestamp: 这是解析ISO时间戳的我的代码:

function isoDateStringToDate (datestr) {
  if (! this.re) {
    // The date in YYYY-MM-DD or YYYYMMDD format
    var datere = "(\\d{4})-?(\\d{2})-?(\\d{2})";
    // The time in HH:MM:SS[.uuuu] or HHMMSS[.uuuu] format
    var timere = "(\\d{2}):?(\\d{2}):?(\\d{2}(?:\\.\\d+)?)";
    // The timezone as Z or in +HH[:MM] or -HH[:MM] format
    var tzre = "(Z|(?:\\+|-)\\d{2}(?:\\:\\d{2})?)?";
    this.re = new RegExp("^" + datere + "[ T]" + timere + tzre + "$");
  }

  var matches = this.re.exec(datestr);
  if (! matches)
    return null;

  var year = matches[1];
  var month = matches[2] - 1;
  var day = matches[3];
  var hour = matches[4];
  var minute = matches[5];
  var second = Math.floor(matches[6]);
  var ms = matches[6] - second;
  var tz = matches[7];
  var ms = 0;
  var offset = 0;

  if (tz && tz != "Z") {
    var tzmatches = tz.match(/^(\+|-)(\d{2})(\:(\d{2}))$/);
    if (tzmatches) {
      offset = Number(tzmatches[2]) * 60 + Number(tzmatches[4]);
      if (tzmatches[1] == "-")
        offset = -offset;
    }
  }

  offset *= 60 * 1000;
  var dateval = Date.UTC(year, month, day, hour, minute, second, ms) - offset;

  return new Date(dateval);
}

Unfortunately, it doesn't handle timezone abbreviations either. 不幸的是,它也不处理时区缩写。 You would have to modify the "tzre" expression to accept letters, and the only solution I know of to deal with timezone abbreviations in Javascript is to have a look-up table which you keep up to date manually in the event of changes to regional daylight savings times. 您将必须修改“ tzre”表达式以接受字母,而我所知的处理Javascript中时区缩写的唯一解决方案是拥有一个查找表,如果更改了区域,则手动更新该查找表夏令时。

EcmaScript formalized the addition of an ISO-8601 style string as an imput for a JavaScript date. EcmaScript正式添加了ISO-8601样式字符串,作为JavaScript日期的输入。 Since most JS implementations don't support this, I created a wrapper to the Date object, that has this functionality. 由于大多数JS实现都不支持此功能,因此我创建了具有此功能的Date对象的包装。 If you set the title tags to output in UTC/GMT/Z/Zulu offset, you can use my EcmaScript 5 extensions for JS's Date object . 如果将标题标签设置为以UTC / GMT / Z / Zulu偏移量输出,则可以将我的EcmaScript 5扩展名用于JS的Date对象

For DateTime values that are to be used in client-side scripts, I generally try to always do the following. 对于要在客户端脚本中使用的DateTime值,我通常会尝试始终执行以下操作。 Store date+time in UTC zone (even in databases). 在UTC区域中存储日期和时间(甚至在数据库中)。 Transmit date-times in UTC zone. 在UTC区域中传输日期时间。 From client to server, you can use the .toISOString() method in the above link. 从客户端到服务器,可以在上面的链接中使用.toISOString()方法。 From server-to client this is relatively easy. 从服务器到客户端,这相对容易。

Via jQuery (with extension): 通过jQuery(带有扩展名):

$('.published').each(function(){
  var dtm = new Date(this.title);
  if (!isNaN(dtm)) {
    this.text(dtm.toString());
  }
});

I don't recall if I added support for non-utc date-times in the input, but wouldn't be too hard to account for them. 我不记得我是否在输入中添加了对非UTC日期时间的支持,但是考虑到它们并不难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 jQuery-如何创建微格式的日期时间 - Jquery - How can i create a datetime in microformat 如何将 JavaScript 中的纪元时间转换为我的当地时间? - How can I convert Epoch time in JavaScript to my local time? 如何在 JavaScript 中将本地日期(没有时间)转换为 UTC DateTime - How to convert local date (without time) in UTC DateTime in JavaScript 将日期时间转换为本地时间 - Convert the DateTime in to Local time 如何在 JavaScript 中将 UTC 日期时间转换为 IST 日期时间 - How can I convert UTC dateTime to IST dateTIme in JavaScript 如何在JavaScript中将不带偏移量的字符串格式的UTC日期转换为本地时间? - How can I convert string formatted UTC dates without offset to local time in JavaScript? 如何将天气 api 转换为当地时间(ReactJS/JavaScript) - How do I convert weather api to local time (ReactJS/JavaScript) 如何将日期时间转换为以毫秒为单位的纪元时间javascript - How to convert datetime to epoch time in milliseconds javascript 如何将UTC时间转换为本地时间 - How to convert a UTC time to local time javascript Javascript:如何倒计时和循环计时器,将日期时间从23:59:59转换为00:00:00 - Javascript: How can I countdown and loop timer, convert datetime time from 23:59:59 to 00:00:00
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM