How To Subtract Minutes from a Date in JavaScript

Subtract Minutes from a Date in JavaScript

To subtract minutes from a date in JavaScript, we have tested effectively with two methods using the getMinutes and setMinutes method and using the subtract method and Moment JS library. Check out the details below to get more information.

Subtract minutes from a date in JavaScript

Using the getMinutes and setMinutes method

An easy way to get the minutes and subtract minutes from a Date is using the getMinutes() to get the minutes from the day, then subtracting minutes and calling to setMinutes() to set the minutes for the day. We already have explained the getMinutes() method in our other article here. Please read it if you want to get more information.

setMinutes syntax:

Date.setMinutes(min, sec, millisec)

Parameters: 

  • min: An integer representing the minutes. (0-59)
  • sec: An integer representing the seconds. (0-59)
  • millisec: An integer representing the milliseconds. (0-999)

Return value: setMinutes sets the minutes of a date.

Code example:

In this example, we can subtract minutes from a date with the get and setMinutes method.

let myDate = new Date('October 31, 2022 12:00:00')
console.log("myDate is: ", myDate)
 
// Using setMinutes and getMinutes method
myDate.setMinutes(myDate.getMinutes() - 10);

console.log("After subtracting 10 minutes from myDate", myDate)

Output

myDate is: 
Mon Oct 31 2022 12:00:00 GMT+0700 
After subtracting 10 minutes from myDate
Mon Oct 31 2022 11:50:00 GMT+0700

Using the subtract() method and Moment JS library

Another simple way to subtract minutes from a date is using the Moment JS library. This library already builds in JavaScript. It helps parse, validate, manipulate, and display date/time in a very easy way. Let’s see the code example below for more information.

Example

import moment from 'moment';

let myDate = new Date('October 31, 2022 12:00:00')
console.log("myDate is: ", myDate)
 
// Using moment library and subtract() method
let newDate = moment(myDate).subtract(10, 'minutes').format();

console.log("After subtracting 10 minutes from myDate:", newDate)

Output

myDate is: 
Mon Oct 31 2022 12:00:00 GMT+0700 
After subtracting 10 minutes from myDate:
2022-10-31T11:50:00+07:00

Summary

In this tutorial, we have explained how to subtract minutes from a date in JavaScript by using two methods: using the getMinutes and setMinutes methods and using the subtract method and Moment JS library. We always hope this tutorial is helpful to you. Leave your comment here if you have any questions or comments to improve the article.

Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *