javascripttypescriptluxon

Parse UK format date string in JS


I'm trying to parse "13/12/2023" or "13/12/2023 10:00:00 AM" date strings to Date objects in JavaScript. As I understand it can not be done via new Date('13/12/2023') as it's expecting a US locale.

I'm trying to use the luxon library to do this work in the following way:

import { DateTime } from 'luxon';
var luxonDate = DateTime.fromFormat("13/12/2023", 'dd/MM/yyyy');

However the above only works for a Date without time. I need to parse time as well. I need to tweak format string to the following:

import { DateTime } from 'luxon';
var luxonDate = DateTime.fromFormat("13/12/2023", 'dd/MM/yyyy h:mm:ss a');

This works for Date with time BUT the problem is that time is optional for me in the string, so the only way I can think of to somehow identify if time passed and use correct format.

Does anyone know if there any other option of not doing it all manually?


Solution

  • You can always check validity after parsing, then try parsing again.

    import { DateTime } from 'luxon';
    
    function parseUKDateWithOptionalTime(s: string) : DateTime {
      let dt = DateTime.fromFormat(s, 'dd/MM/yyyy h:mm:ss a');
      if (!dt.isValid) {
        dt = DateTime.fromFormat(s, 'dd/MM/yyyy');
      }
    
      return dt;
    }
    

    Though - do keep in mind that when you parse a date without a time into a Luxon DateTime object, you're implying that you want the time to be 00:00 (midnight). Fundamentally, that's a different concept than a date (which would include all times within the day, not just midnight). The JavaScript Date object has the same issue (it's really a timestamp, not a date).

    Thus, you might consider not using this function, but instead breaking apart your business logic into different paths. Ask yourself what it actually means when someone provides a whole date and how that differs than providing a date and time. For example, a whole date might indicate a birth day to acknowledge any time within the day, or a business day in which a discount is valid through the end of the day. Whereas a date and time usually indicates an exact point at which something occurred or will occur.