Vishwajith H H
Vishwajith H H

Reputation: 13

Is there a general way to initialise any format of date and time with luxon

When switching from moment to luxon, I found out this initialisation issue.

In moment, we can initialise all date and time formats without writing a from condition for each type.

moment(timestamp), moment(new Date()), moment(timeString)

Even in native javascript, we can initialise without writing any condition for each format new Date(value)

But, in luxon, we must write a from condition for each format of data.

DateTime.fromMillis(timestamp), DateTime.fromJSDate(new Date), DateTime.fromISO(timeString)

Is there a method in luxon where we can write a generic method of initialising any date format without separate condition ?

I tried of using this template

var input = new DateTime(value) // value is either timestamp, timeString or JS date

But this gives only current time without parsing the value

Upvotes: 1

Views: 729

Answers (1)

moonwave99
moonwave99

Reputation: 22812

You can write it yourself:

function getDate(input) {
  if (input instanceof Date) {
     return DateTime.fromJSDate(input);
  }
  if (typeof input === 'string') {
    return DateTime.fromISO(input);
  }
  return DateTime.fromMillis(input);
}

Better would be to check if input is numeric in the last case, and throw an exception as the fallback case.

Upvotes: 1

Related Questions