Search code examples
javascriptluxon

Formatting Strings to Datetime using specific formats in Luxon


By now I used moment-js for time handling, but I want to switch to Luxon. But I have problems with the following implementation.

There is a textfield where you can enter a datetime in your locale time format, for instance HH:mm (24h format) or hh:mm (12h format). The used time format is stored in the variable timeFormat.

My solution with moment-js:

let timeFormat = 'HH:mm' // 'hh:mm a'
let textfield = document.querySelector('#input-time');
let timeString = textfield.value;
let dateTime = moment(timeString, timeFormat, true);

// Check if time is valid
if(dateTime.isValid() === false){
    return;
}

Using 12h-format:

  • 11:00 am, 09:43 pm are valid.
  • 11:00, 21:43 are invalid.

Using 24h-format:

  • 11:00 am, 09:43 pm are invalid.
  • 11:00, 21:43 are valid.

How can I aprove obtain a similar solution with Luxon? My biggest issue is to get a similar function to moment(timeString, timeFormat, true), so formatting a String into a Datetime using a specific format, for instance 12h/24-format.


Solution

  • You can use fromFormat method

    Create a DateTime from an input string and format string. Defaults to en-US if no locale has been specified, regardless of the system's locale.

    Example:

    const DateTime = luxon.DateTime;
    const inputs = ['11:00 am', '09:43 pm', '11:00', '21:43'];
    const formats = ['HH:mm', 'hh:mm a'];
    
    const checkTime = (timeString, fmt) => 
      DateTime.fromFormat(timeString, fmt).isValid
    
    
    for (i=0; i<inputs.length; i++) {
      for (j=0; j<formats.length; j++) {
        console.log(`${inputs[i]} with format '${formats[j]}' is valid? ` + checkTime(inputs[i], formats[j]) );
      }
    }
    <script src="https://cdn.jsdelivr.net/npm/luxon@1.25.0/build/global/luxon.js"></script>

    Have a look at For Moment users section of the manual for good reference to migrate from momentjs to Luxon.