skip to Main Content

I have an example datetime string "Today, Fri May 12 2023 at 07:00:00, we go swimming". I use the new Date(string) and it gives invalid date.

Is there regex script to convert that string to valid date?

3

Answers


  1. You can of course convert a string if you know it follows that exact form. But I suppose that’s not the case and you’re looking for the ability to parse various sentences in free-form english that contain date and time information.

    Parsing free-form language can’t be done by a classic algorithm, with or without a regex. Humans can do so, and an AI can be trained to do so as well. You can send the sentence to ChatGPT’s API for example, with a prompt asking it to return the date in standardized form. Even then, there might be sentences which are worded in a confusing way and would be interpretted wrong.

    Login or Signup to reply.
  2. ^(Today,)? ([A-Z]{3}) ([a-z]{3}) ([0-9]{2}) ([0-9]{4}) at ([0-9]{2}):([0-9]{2}):([0-9]{2}), (.*)$
    

    Once the regex has matched the string, use the following code to convert it to a valid date:

    DateTime date = DateTime.ParseExact(
    matchedString,
    "dd MMM yyyy HH:mm:ss",
    CultureInfo.InvariantCulture
    );
    

    The string will be parsed into a DateTime object using the DateTime.ParseExact() method in this code. The ‘CultureInfo.InvariantCulture’ argument specifies that the date should be parsed using the invariant culture, which is the culture that is independent of the user’s location.

    Login or Signup to reply.
  3. I’d suggest sanitizing your input(s), then using a dedicated datetime module such as luxon to parse the result.

    We’d split and filter the string using a custom sanitizeInput function then use DateTime.fromFormat to parse it.

    const { DateTime } = luxon;
    const months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
    
    function dateComponentFilter(x) {
        x = x.toLowerCase();
        if (/d{2,4}/.test(x)) { 
            return true;
        }
        if (/d{2}:d{2}:d{2}/.test(x)) { 
            return true;
        }
        if (months.find(month => month === x)) { 
            return true;
        }
        return false;
    }
    
    function sanitizeInput(input) {
        return input.split(/[,s]/).filter(dateComponentFilter).join(' ')
    }
    
    
    const input = 'Today, Fri May 12 2023 at 07:00:00, we go swimming';
    console.log('Input:          ', input);
    
    const sanitizedInput = sanitizeInput(input);
    console.log('Sanitized input:', sanitizedInput);
    
    const d = DateTime.fromFormat(sanitizedInput, 'MMM dd yyyy HH:mm:ss');
    console.log('Parsed date:    ', d.toFormat('yyyy-MM-dd HH:mm:ss'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.3.0/luxon.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search