skip to Main Content

Dates are really weird, and I can’t seem to solve this issue:

I live in GMT+2 time zone. My server saves everything in UTC time zone.

I set date from my website to 2024-12-01 which is converted to UTC time 2024-11-30T22:00:00.000Z

I need to get the next month date which should be:

Server response: 2024-12-31T22:00:00.000Z; and client should see: 2024-01-01

But the server will return me:

Server response: 2024-12-30T22:00:00.000Z; and client will see: 2024-12-31

Because by using date.setMonth(date.getMonth() + 1) server will take November (30) month days instead of December (31)

The question is how to get the correct next month date without knowing client time zone?

Thanks for any help!

2

Answers


  1. I am confused but, can you try this to see if this is what you want;

    // date as YYYY-MM-DDT00:00:00Z
    var date = new Date("2024-12-01T00:00:00Z");
    
    let dateFormat = new Date(new Date(date).setMonth(date.getMonth() + 1));
    
    dateFormat.setMinutes(dateFormat.getMinutes() + dateFormat.getTimezoneOffset())
    
    let dateStr = dateFormat.toLocaleDateString();
    
    console.log(dateStr)
    Login or Signup to reply.
  2. You need the month or the date? What is the date next month? It will fail going from months with more days to months with less days if the day is > 28.

    Your issue is when the day does not exist in the next month.

    I normally (pun intended) normalise on 15:00 to not run into timezone issues

    function getNextMonth(dateStringUTC) {
      const date = new Date(dateStringUTC);
    
      // Normalize to the 1st at 15:00 UTC to avoid time zone and DLS issues
      date.setUTCDate(1); // Set to the 1st
      date.setUTCHours(15, 0, 0, 0); // Set time to 15:00:00
    
      // Add one month
      date.setUTCMonth(date.getUTCMonth() + 1);
    
      return new Intl.DateTimeFormat('en-US', { month: 'long' }).format(date);
    }
    
    
    const inputDate = "2024-11-30T22:00:00.000Z";
    console.log(getNextMonth(inputDate)); // Expected: December
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search