JQuery Moment JS Subtract Hours to Datetime Example

By Hardik Savani | December 31, 2020 | Category : jQuery


This article goes in detailed on jquery moment subtract hours. you will learn moment js subtract hours to time. This article will give you simple example of moment subtract hours to current time. this example will help you moment js subtract hours to current time.

Here, i will give you simple example of jquery moment js add() method for add hours to date and jquery moment js subtract() method for subtract hours from date.

let's see both example with output:

Example 1: Subtract Hours to Time

<!DOCTYPE html>

<html>

<head>

<title>JQuery Moment Add Hours Example - ItSolutionStuff.com</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" crossorigin="anonymous"></script>

</head>

<body>

<h1>JQuery Moment Add Hours Example - ItSolutionStuff.com</h1>

</body>

<script type="text/javascript">

var startDateTime = '26-12-2020 09:30:20'

var newDateTime = moment(startDateTime, "DD-MM-YYYY hh:mm:ss")

.subtract(2, 'hours')

.format('DD/MM/YYYY hh:mm:ss');

console.log(newDateTime);

var currentDateTime = moment().subtract(2, 'hours')

.format('DD/MM/YYYY hh:mm:ss');

console.log(currentDateTime);

</script>

</html>

Output:

26/12/2020 07:30:20

31/12/2020 07:28:57

Example 2: Add Hours to Time

<!DOCTYPE html>

<html>

<head>

<title>JQuery Moment Add Hours Example - ItSolutionStuff.com</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" crossorigin="anonymous"></script>

</head>

<body>

<h1>JQuery Moment Add Hours Example - ItSolutionStuff.com</h1>

</body>

<script type="text/javascript">

var startDateTime = '26-12-2020 09:30:20'

var newDateTime = moment(startDateTime, "DD-MM-YYYY hh:mm:ss")

.add(2, 'hours')

.format('DD/MM/YYYY hh:mm:ss');

console.log(newDateTime);

var currentDateTime = moment().add(2, 'hours')

.format('DD/MM/YYYY hh:mm:ss');

console.log(currentDateTime);

</script>

</html>

Output:

26/12/2020 11:30:20

31/12/2020 11:27:14

I hope it can help you...



Tags : jQuery Moment JS


Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: