Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  12] [ 3]  / answers: 1 / hits: 6308  / 4 Years ago, mon, november 2, 2020, 12:00:00

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.


More From » luxon

 Answers
8

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/[email protected]/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.


[#2381] Tuesday, October 27, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tobyl

Total Points: 598
Total Questions: 110
Total Answers: 114

Location: Vietnam
Member since Sat, Feb 12, 2022
2 Years ago
tobyl questions
Tue, Aug 10, 21, 00:00, 3 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Tue, Dec 1, 20, 00:00, 4 Years ago
;