gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
Javascript Date Parse with specific locale
- User
Javascript Date Parse with specific locale
- Assistant
To parse a date in a specific locale, you can use the
Intl.DateTimeFormatconstructor 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/2021In the example above, we're using
Intl.DateTimeFormatto format the date to the same format as the input string (MM/DD/YYYY). Theoptionsobject specifies the format we want, and we're passing the locale (in this case,en-US) as the first argument when creating theDateTimeFormatobject.Note that the
Date.parsemethod 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 byDate.parse. In the example above, we're assuming the format isMM/DD/YYYY.