0

For example, there is a time value like below.

const currentDate = '2019-10-21 21:33'

And I want to add some specific minute to this date.

const addMinute = '70'

In result, I want to get,

const totalMinute = '2019-10-21 22:43'

How can I get this value using just simple sum? or using 'moment module' Thank you so much for reading it.

1
  • Kindly post some of your code in which you are receiving the error. Commented Nov 19, 2019 at 6:24

2 Answers 2

1
const currentDate = '2019-10-21 21:33'
const addMinute = 70
const totalMinute = new Date(currentDate).setMinutes(new Date(currentDate).getMinutes()+ addMinute)
const totalDate = new Date(totalMinute)
1

Here is a ultra-simple example on how can you do that with a simple sum.

Note: this will not modify the date part if needed, but you can use a similar logic to accomplish that.

const currentDate = '2019-10-21 21:33'
const addMinute = '70'
const totalMinute = '2019-10-21 22:43'

const addMin = (datetime, min) => {
  min = parseInt(min);
  // Parse the datetime string
  const date = datetime.split(' ')[0]
  const time = datetime.split(' ')[1]
  // Parse the time string and cast each part to an integer
  const hours = parseInt(time.split(':')[0])
  const minutes = parseInt(time.split(':')[1])
  // Figure out how many hours and minutes are to be added
  const hoursToAdd = Math.floor(min / 60);
  const minsToAdd = min % 60;
  // Return the new datetime string
  return date + ' ' + (hours + hoursToAdd) + ':' + (minutes + minsToAdd);
}

console.log(addMin(currentDate, addMinute));

Otherwise you can use the JS Date object:

const currentDate = '2019-10-21 21:33'
const addMinute = '70'
const totalMinute = '2019-10-21 22:43'

const addMin = (datetime, min) => {
  min = parseInt(min);
  const date = new Date(datetime);
  const newDate = new Date(datetime);
  const minsToAdd = date.getMinutes() + min
  
  newDate.setMinutes(minsToAdd);
  
  return newDate.toISOString().substr(0,10) + ' ' + newDate.toTimeString().substr(0,5);
}

console.log(addMin(currentDate, addMinute));

1
  • it will not work with date changes / leap seconds / daylight saving time changes
    – Adassko
    Commented Nov 19, 2019 at 6:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.