skip to Main Content

I am trying to perform a simple JavaScript logic where our business wants to ‘freeze’ the time before reaching the deadline on the case they are working.

Eg:

Deadline: 04/07/2024 5:00 PM EST
Freeze Datetime: 04/04/2024 2:00 PM EST
Unfreeze Datetime: 04/05/2024 2:00 PM EST
New Deadline: 04/08/2024 5:00 PM EST (i.e., Unfreeze Datetime + Duration[Deadline-Freeze Datetime] )

Here is the logic I’ve implemented so far:

let freezeStartDate = new Date(<< Getting from an Audit record>>);
let currentDeadline = new Date(<< Current Deadline Datetime>>);
let diffMs = currentDeadline - freezeStartDate;
let diffMins = Math.round(diffMs/60000);
console.log('diffMins: ' +diffMins);

let curDate = new Date(currentDateTime); //Passed down as an param
let newDeadline = new Date(curDate + diffMins);
console.log('newDeadline : ' +newDeadline ); //Getting same as curDate

I am not sure if I am missing some additional conversions or formatting. Any insights are highly appreciated.

2

Answers


  1. Look at the API reference.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

    new Date(value)

    value

    An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most UNIX Timestamp functions are only accurate to the nearest second.

    In your case:

    let newDeadline = new Date(curDate[This is in millis] + diffMins[This is in minutes] );

    You can use any higher order date library that handles the complexity and lets you simply .addMinutes and gives you a new date.

    Refer – https://stackoverflow.com/a/1214753/1193808

    Or.

    Convert everything into millis and then add them

    Login or Signup to reply.
  2. Adding minutes to a date object, you cannot simply add the number of minutes to the date object directly. Instead, you can use the setMinutes() method of the date object to add the minutes to the date.

    Something like this:

    let newDeadline = new Date(curDate.getTime() + diffMs);
    newDeadline.setMinutes(curDate.getMinutes() + diffMins);
    

    If you need to use a different current date, you can pass it to the Date() constructor instead of using new Date().

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