Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

Javascript Date Parse with specific locale

  1. User

    Javascript Date Parse with specific locale

  2. Assistant

    To parse a date in a specific locale, you can use the Intl.DateTimeFormat constructor and pass the locale as an option. Here's an example:

    const dateString = '10/31/2021'; // assuming MM/DD/YYYY format
    const locale = 'en-US'; // US English locale
    
    const options = {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    };
    
    const formattedDate = new Intl.DateTimeFormat(locale, options).format(new Date(Date.parse(dateString)));
    console.log(formattedDate); // output: 10/31/2021
    

    In the example above, we're using Intl.DateTimeFormat to format the date to the same format as the input string (MM/DD/YYYY). The options object specifies the format we want, and we're passing the locale (in this case, en-US) as the first argument when creating the DateTimeFormat object.

    Note that the Date.parse method does not support all date formats, so it's important to make sure the input date string is in a format that can be parsed by Date.parse. In the example above, we're assuming the format is MM/DD/YYYY.