Home > Mobile >  NodeJS: Check if day is sunday - TZ offset problem
NodeJS: Check if day is sunday - TZ offset problem

Time:05-17

I would like to restrict some actions if date is on sunday - e.g. do not allow create item on Sunday.

I use:

public isSunday(date: Date): boolean {   
  return date.getDay() === 0; 
}

My problem is that my UTC offset is UTC 2.
Server and database runs on UTC TZ to prevent unwanted date and time shifts.

When I send datetime from frontend I use date.toISOString(), so my local datetime

2022-05-16 00:00:00 is converted to string 2022-05-15T22:00:00:000Z

When I check this date on the backend side, this date IS sunday, but in the UTC zone, not my local zone.

String value is converted to Date at the backend using following new Date(input);

Edit: Value 2022-05-16T01:41:00 02:00 (sending value with utc offset info) does not work either

CodePudding user response:

To my understanding, you need the local (UTC 2) zone on the back-end for only Sunday checks.

You can simply subtract 2 hours equal to milliseconds from the date received on the backend before the Sunday checks.

// ... get date here
date -= (2 * 60 * 60 * 1000); // subtract 2 hours

CodePudding user response:

I don't think this is a good practice as your frontend may change its timezone but you can try this.

const date = new Date("2022-05-16 00:00:00")
const corrected_date = new Date(date.valueOf() - 7200000) //subtract milliseconds as needed, in this case 2*60*60*1000
console.log(corrected_date.getDay())

If possible, then you should maybe try sending the UTC offset as a seperate parameter to the backend and calculate the correct value to be subtracted for it to work dynamically.

  • Related