0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Austin Evans
  • 129
  • 5

2 Answers2

0

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().

user16217248
  • 3,119
  • 19
  • 19
  • 37
  • Almost. Don't add *diffMs* in the first line, just use `let newDeadline = new Date(currDate)`. The use of *getTime* or *valueOf* is redundant (though perhaps adds clarity). – RobG Apr 05 '23 at 08:59
-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

Subir Kumar Sao
  • 8,171
  • 3
  • 26
  • 47
  • The *Date* constructor expects a number representing milliseconds, so `diffMins * 6e4` is indicated. But, adding time as milliseconds is not suitable where it's possible that the interval crosses a change of offset boundary, either historic or daylight saving. To add minutes correctly, use *setMinutes* per @LLeonaro's answer. – RobG Apr 05 '23 at 08:56