Converting string date to its corresponding day of the week not workin as expected in Javascript

36 Views Asked by At

I'm having a bit of problem with a date conversion in JavaScript. I have string in format "2023-12-14" that I would like to convert to its corresponding Day of week in a Vue template( In this instance Thursday). I am using this formula :

{{ new Date("2023-12-14").toLocaleString('en-us', {
            timeZone: 'America/New_York',
            weekday: 'long'
        }) }}

Unfortunately this is printing out Wednesday instead of Thursday. I figure it has something to do with the UTC but I have included timezone parameter in .toLocaleString but still printing wrong date. It is the same with several other dates I need to convert, they all print out a day earlier then expected. Any help would be much appreciated...

Update Info: My template is

{{new Date(gameScores[n -
        1].parameters.date).toLocaleString('en-us', {
            timeZone: 'America/New_York',
            weekday: 'long'
        }) }}

Can I output the correct day of week from the template expression?

2

There are 2 best solutions below

0
jsejcksn On

You can write a functional abstraction to parse the date numerically before using the Date() constructor. Modify if needed to suit your needs:

function getWeekdayName(dateStr) {
  // Validate input:
  if (!(/^\d{4}-\d{2}-\d{2}$/).test(dateStr)) {
    throw new Error("Unexpected input format");
  }
  return new Date(
    Number(dateStr.slice(0, 4)),     // year
    Number(dateStr.slice(5, 7)) - 1, // month index
    Number(dateStr.slice(8, 10)),    // day of month
  ).toLocaleString("en-US", { weekday: "long" });
}

const dateStr = "2023-12-14";
const weekdayName = getWeekdayName(dateStr);
console.log(weekdayName);

0
Ozone On

A date in JS is a timestamp under the hood. Since you are not defining a time with that date it defaults to midnight. The locale can then be off by a number of hours, resulting in an unexpected day being returned.

By parsing date from a string, I believe the timezone will default to UTC. The client then makes up for the UTC time difference and can be a day off (since you did not specify a time, it assumes midnight UTC). You can make JS use the local time instead of the default UTC by setting the date with numbers as parameters instead of a string.

So rather than doing:

let date = new Date("2023-12-14")

You'd do:

let date = new Date(2023,11,14) // mind the month