skip to Main Content

I have the date as follows,

let date = '2024-03-11';

I want to add plus 1 day to above date

let newDate = mew Date(date); -> converting to local date -> 2024-03-10 (becoming -1)
newDate.setDate(newDate.getDate() + 1);

It worked well but the problem is I am getting the local date when I am using new Date() method which is converting my date to 2024-03-10

Can some one help me how to add 1 date to UTC date without getting it converted to local time zone.

3

Answers


  1. To add one day to a UTC date without converting it to the local time zone, you can use the Date.UTC() method along with the Date object constructor. Here’s how you can do it:

    let date = '2024-03-11';
    let parts = date.split('-');
    let utcDate = new Date(Date.UTC(parts[0], parts[1] - 1, parts[2])); // Months are zero-indexed, so subtract 1 from the month
    
    // Add one day
    utcDate.setUTCDate(utcDate.getUTCDate() + 1);
    
    // Format the new date
    let newDate = utcDate.toISOString().slice(0, 10);
    console.log(newDate); // Output: 2024-03-12
    

    This code creates a new Date object with UTC time and adds one day to it without converting it to the local time zone.

    Login or Signup to reply.
  2. To add 1 day to a UTC date without it getting converted to the local timezone, you can directly manipulate the date string or use the Date.UTC method to ensure the operation is performed in UTC. Here’s a method that modifies the date string and creates a new date object in UTC:

    let dateStr = '2024-03-11';
    
    // Parse the date string and create a Date object in UTC
    let date = new Date(Date.UTC(
      parseInt(dateStr.substring(0, 4), 10),  // Year
      parseInt(dateStr.substring(5, 7), 10) - 1, // Month (0-based)
      parseInt(dateStr.substring(8, 10), 10)   // Day
    ));
    
    // Add 1 day in milliseconds
    date.setTime(date.getTime() + (24 * 60 * 60 * 1000));
    
    // Format the new date back to a string in YYYY-MM-DD format
    let newDate = date.toISOString().substring(0, 10);
    
    console.log(newDate);
    
    Login or Signup to reply.
  3. for nodejs, you can use moment:

    const moment = require("moment");
    
    let date = "2024-03-11";
    
    let utcTime = moment.utc(date);
    
    let plusTime = utcTime.add(1, "day");
    
    let result = plusTime.format("YYYY-MM-DD");
    
    console.log(result);
    // 2024-03-12
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search