【问题标题】:Convert GMT to IST (India Standard Time) using javascript?使用 javascript 将 GMT 转换为 IST(印度标准时间)?
【发布时间】:2020-05-02 02:39:44
【问题描述】:

我的日期格式是 GMT 或 UTC。

var mydate  = '2020-01-14T17:43:37.000Z'

我想将此日期转换为 IST 格式,因此根据此日期,我需要此格式的输出。

var date = '2020-Jan-15 12:45'


【问题讨论】:

  • 该开始日期既不是 PST 也不是 PDT。它是 GMT(如果您愿意,也可以是 UTC)。
  • 使用带有时区的momentjs,如果时间是UTC,那么只需将分钟添加到时间戳

标签: javascript date timezone utc pst


【解决方案1】:

您可以在传递给toLocaleString 的选项中指定 IANA 时区标识符。印度的标识符是Asia/Kolkata

var s = new Date('2020-01-14T17:43:37.000Z').toLocaleString(undefined, {timeZone: 'Asia/Kolkata'});

这将进行正确的时区转换,因为输入是 UTC(由末尾的 Z 指定)。

undefined 表示使用用户的区域设置来格式化日期和时间。这通常是你想要的。如果您想要更特定的格式(如您在问题中指定的格式),您可以提供特定的语言环境字符串和/或调整toLocaleString 的其他选项,如给定的in the docs

另外,请注意您问题中的转换不正确。印度与 UTC 相差 5 小时 30 分钟。因此正确的输出是2020-01-14 23:13:37(你喜欢的任何格式)

【讨论】:

  • 小问题:IANA 使用亚洲/加尔各答等“代表性位置”,因为并非同一时区的所有地方都使用相同的历史或夏令时偏移量。 ;-)
  • @RobG - 有争议的术语,当然。 tzdb 中的theory file 在标题中称它们为“标识符”。它们在tz-link file 中也称为“条目”。我更喜欢“标识符”,因为它们唯一地标识了一个时区,并且适合存储在数据库中的类或字段中的“ID”属性等中。:)
  • 当然,但它标识了一个代表位置,该位置具有一组特定的时区偏移规则和时区内某个地方或行政区域的历史记录,它不是时区标识符本身。 :-)
【解决方案2】:

您的另一个选择是使用momentmoment timezone 模块进行时区转换,它们非常灵活,您可以根据您希望的任何格式格式化生成的日期对象。

正如@matt-johnson-pint 所提到的(谢谢!),您也可以为此使用非常酷的Luxon 库,我在下面添加了一个示例。

const mydate  = "2020-01-14T17:43:37.000Z"

// Create a UTC date object. The moment constructor will recognize the date as UTC since it includes the 'Z' timezone specifier.
let utcDate = moment(mydate);

// Convert the UTC date into IST
let istDate = moment(mydate).tz("Asia/Kolkata");

console.log("Using Moment.js:");
console.log(`UTC date (iso): ${utcDate.format("YYYY-MM-DD HH:mm:ss")}`);
console.log(`IST date (iso): ${istDate.format("YYYY-MM-DD HH:mm:ss")}`);

const DateTime = luxon.DateTime;

utcDate = DateTime.fromISO(mydate);
istDate = DateTime.fromISO(mydate).setZone("Asia/Kolkata");

console.log(`\nUsing Luxon:`);
console.log(`UTC date (iso): ${utcDate.toFormat("yyyy-LL-dd HH:mm:ss")}`);
console.log(`IST date (iso): ${istDate.toFormat("yyyy-LL-dd HH:mm:ss")}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-1970-2030.js"></script>
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

【讨论】:

  • 仅供参考,作为 Moment 和 Moment-Timezone 的维护者 - 我们建议您使用 Luxon 进行所有新开发。考虑在维护模式下的时刻。谢谢。 (请随时在您的回复中添加 Luxon 示例。)
  • 非常感谢您提供的信息。我将继续使用 Luxon!
猜你喜欢
  • 2013-10-03
  • 2012-12-25
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 2019-05-23
  • 2013-11-19
相关资源
最近更新 更多