【问题标题】:Convert an iso8601 time string to the current timezone in JS在 JS 中将 iso8601 时间字符串转换为当前时区
【发布时间】:2021-11-10 11:15:09
【问题描述】:

我在应用中使用https://fullcalendar.io/ 日历插件。我为日历提供了 iso8601 格式的日期数据,例如 "2021-09-15T14:30:00+01:00",日历很好地显示了针对浏览器中设置的时区调整的时间。

例如,如果浏览器位于“+01:00”时区,则该时间显示为 14:30,但如果它位于“+02:00”时区,则显示为 15:30,等等。

我的问题是我想在日历之外的其他上下文中显示这些时间,并且我不想从服务器输出不同的东西 - 我希望使用 javascript 在浏览器中进行转换.

我突然想到我可以做这样的事情:在数据属性中使用 iso861 字符串输出时间跨度,也许还有一个类作为页面上某些通用 js 的触发器。但是,在 JS 中是否有一种简单的方法可以使用浏览器的时区设置将 iso8601 时间字符串转换为时间?我想我需要另一个数据属性,其中包含一些关于我希望如何格式化的信息,例如"%H:%M" 在这种情况下(如果我想输出“14:30”或“15:30”)。

注意 - 我们使用 jquery,我将在下面的示例 JS 中使用它。

类似这样的:

<!-- in html - the span contains the default unconverted time -->

<span class="convertable-time" data-iso8601="2021-09-15T14:30:00+01:00" data-datetime-format="%H:%M">14:30</span>

然后在 JS 中是这样的(这是使用 jquery 但解决方案不需要)

$(".convertable-time").each(function(i,el){
  el = $(el);
  el.html(convertIso8601StringToLocalTime(el.data("iso8601"), el.data("datetime-format"));
});

function convertIso8601StringToLocalTime(string, format){
  //eg string = "2021-09-15T14:30:00+01:00"
  //eg format = "%H:%M"
  // ??
}

我会在convertIso8601StringToLocalTime 函数中添加什么? 注意 - 我不喜欢“%H:%M”的确切格式字符串,如果有更标准的方式在 JS 中指定日期时间格式,那么我很乐意使用它。谢谢。

【问题讨论】:

标签: javascript datetime browser timezone iso8601


【解决方案1】:

这就是我最终做的:

//expects timestring to be an iso8601 formatted datetime string eg "2021-09-15T14:30:00+01:00"
//accepted strings for "format": copied from ruby's DateTime#strftime method
// %M - minutes
// %H - hours
// %S - seconds
// %d - day of the month
// %Y - year four digits
// %y - year two digits
// %m - month (as a number)
function convertIso8601StringToLocalTime(timestring, format){
  //set default format
  if((typeof(format) == "undefined") || (format == "")){
    format = "%H:%M";
  }
  var date = new Date(timestring);
  var replacements = {
    "getMinutes": /\%M/g,
    "getHours": /\%H/g,
    "getDate": /\%d/g,
    "getFullYear": /\%Y/g,
    "getMonth": /\%m/g
  }
  for (const [function_name, regex] of Object.entries(replacements)) {
    if(format.match(regex)){
      format = format.replace(regex, date[function_name]());
    }
  }
  // year two digits doesn't have a method we can call on a Date as far as I can see
  // ('getYear()' returns '121' for me which is mysterious)
  // so we do it 'manually' here by modding the full year by 100
  if(format.match(/\%y/g)){
    format = format.replace(/\%y/g, (date.getFullYear() % 100));
  }
  return format;
}

【讨论】:

  • 所以你只是想要一个简单的格式化程序?有一个here 使用 PHP 令牌,我认为转换为其他令牌方案应该相当简单。 ECMAScript 允许使用默认参数,因此您可以使用 function convertIso8601StringToLocalTime(timestring, format = '%H:%M'){...} 代替 if (typeof format == 'undefined'...) 等。 :-)
  • 谢谢 - 我没有输入默认参数的原因是我认为格式有时可能会以空字符串的形式出现,并希望将其视为等同于“未定义”情况,默认参数不会这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多