skip to Main Content

So I may be looking at this entirely wrong, but essentially I need to add x amount of hours to a JavaScript date which i’ve done using this function:

export function addHoursToDate(hoursFromNow: number = 5)
{
  return new Date(new Date().setTime(new Date().getTime() + (hoursFromNow*60*60*1000)));
}

(This is based on an answer I saw on this site as well) and that does work fine, the problem is I need to convert it to this format:

"2023-10-25T15:00:00.000Z" (for example) which I understand is the standard date/time format. Usually I use toIsoString() problem is when I do that it converts it to UTC.

Essentially I need to be able to add x/y hours/minutes to the date but have it in the datetime format as above? Im sure im missing something obvious but I wanted to see if there was a clean way to do this. But also maybe im thinking about it the wrong way as well.

2

Answers


  1. Trivial if the output stays ISO

    const addHours = (dateString, hoursToAdd) => {
      const originalDate = new Date(dateString);
      originalDate.setHours(originalDate.getHours() + hoursToAdd);
      return originalDate.toISOString();
    };
    
    const result = addHours("2023-10-25T15:00:00.000Z", 3); // Example: Adding 3 hours
    console.log(result);

    From now

    const addHoursToLocalTime = (hoursToAdd) => {
      const originalDate = new Date();
      originalDate.setHours(originalDate.getHours() + hoursToAdd);
      return originalDate.toISOString();
    };
    
    console.log(new Date().toISOString()); // to show what "now" is in ISO format
    const result = addHoursToLocalTime(3); // Example: Adding 3 hours to the current local time
    console.log(result);
    Login or Signup to reply.
  2. You can use moment.js (https://momentjs.com/) to achieve the same what you are looking for,

    Here is how you do it using momentjs library

    let timestring = "2013-05-09T00:00:00Z";
    let returned_date = moment(timestring).add(2, 'hours');  
    // You can add hours/minutes to the date
    

    Check out the official documentation for more in depth details – https://momentjscom.readthedocs.io/en/latest/moment/03-manipulating/01-add/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search