Dennis
Dennis

Reputation: 1975

how to import an UTC timestamp to Luxon as it is? (Migrating from Moment)

I have this line in my app:

const createdOn: moment.Moment = moment.utc(created_on)

created_on comes from an api endpoint like in this format:

{ 
  ...,
  created_on: "2019-03-08T15:32:26.285Z",
}

This basically imports created_on as an UTC timezone. created_on is also UTC. So, this method does not break the timezone and import UTC properly. Also I have this one:

That generates current timestamp in UTC timezone.

moment.utc()

Note that, If I just import date to moment and then convert it to UTC, my time goes wrong. Moment by default assumes given date is equal to current visitors timezone. I need to import time as it is. Which is UTC all the time.

What is the equivelant on Luxon?

Upvotes: 2

Views: 4831

Answers (1)

VincenzoC
VincenzoC

Reputation: 31502

You can use DateTime.utc and you can have a look at For Moment users section of Luxon's manual.

You can find in the Creation section:

Operation           | Moment            | Luxon                   | Notes
------------------------------------------------------------------------------------
From UTC civil time | moment.utc(Array) | DateTime.utc(Number...) | Moment also uses moment.utc() to take other arguments. In Luxon, use the appropriate method and pass in the { zone: 'utc'} option

So, if your input is a string, you can use from method (like fromISO) using {zone: 'utc'} option

Here a live sample:

const DateTime = luxon.DateTime;
const nowLuxon = DateTime.utc();
console.log(nowLuxon.toISO(), nowLuxon.toMillis());

const nowMoment = moment.utc();
console.log(nowMoment.format(), nowLuxon.valueOf());

const created_on = "2019-03-08T15:32:26.285Z";
const createdOnLuxon = DateTime.fromISO(created_on, { zone: 'utc'});
console.log(createdOnLuxon.toISO(), createdOnLuxon.toMillis());

const createdOnMoment = moment.utc(created_on);
console.log(createdOnMoment.format(), createdOnMoment.valueOf());
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Upvotes: 6

Related Questions