最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parse dateTime string as UTC - Stack Overflow

programmeradmin9浏览0评论

Timezones is constant pain in every datetime library I tried. So here's the question, suppose you have a UTC datetime provided as string: 2019-06-25T05:00:00Z. How do you create a UTC DateTime object out of it (I use luxon, but answer can be in terms of any library)?

console.info(luxon.DateTime.fromISO('2019-06-25T05:00:00Z').toSQL());
<script src=".min.js"></script>

Timezones is constant pain in every datetime library I tried. So here's the question, suppose you have a UTC datetime provided as string: 2019-06-25T05:00:00Z. How do you create a UTC DateTime object out of it (I use luxon, but answer can be in terms of any library)?

console.info(luxon.DateTime.fromISO('2019-06-25T05:00:00Z').toSQL());
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

When I run the snippet above I get:

2019-06-25 09:00:00.000 +04:00 // local timezone

While I need:

2019-06-25 05:00:00.000 -00:00 // UTC
Share Improve this question edited Jun 8, 2020 at 12:14 jayarjo asked Jun 8, 2020 at 11:38 jayarjojayarjo 16.8k25 gold badges100 silver badges148 bronze badges 1
  • 1 Looks like you have to tell it to use UTC as the zone for the instance. It parses the string correctly, it's just using your local timezone when building a new string. I've updated my answer to show how to do that. – T.J. Crowder Commented Jun 8, 2020 at 12:24
Add a ment  | 

1 Answer 1

Reset to default 6

Three options for you:

1) Luxon's documentation says you could use fromISO to get a DateTime from it. That parses the string correctly. Looks like to get it formatted the way you want, you have to tell it to use the zone UTC, but that's because it's formatting on output:

const {DateTime} = luxon;
console.info(DateTime.fromISO('2019-06-25T05:00:00Z', { zone: "UTC"}).toSQL());
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

You could also use setZone("UTC") on the result of fromISO.

2) JavaScript's built-in Date object will parse that as UTC (new Date(yourString)), since it's in the format defined in the spec. You can then use the UTC methods on it to get the UTC information (getUTCHours, etc.), or you can use the local date/time methods on it to get the local information (getHours, etc.). You can also use toISOString to get a UTC string:

console.info(new Date('2019-06-25T05:00:00Z').toISOString());
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

3) Moment would also happily do so.

console.info(moment.utc('2019-06-25T05:00:00Z').toISOString());
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.26.0/moment.min.js"></script>

If you need +00:00 instead of Z, you can throw a replace at it, or with Luxon or Moment they offer full formatting options.

发布评论

评论列表(0)

  1. 暂无评论