Menu

  • Home
  • Trending

CATEGORIES

  • Stock Market & Trading
  • Banking & Finance
    • Banking
    • Credit and Debit Cards
  • Business & Startups
    • Business Basics
    • Business ideas
  • Cooking & Food
    • Easy Healthy Meals
  • Education
    • Business Skills
    • Content Writing Skills
    • Digital Marketing
  • Fashion & Lifestyle
    • Fashion
  • Freelancing
    • Finance & Accounting
  • Health & Fitness
    • Health
    • Health care
    • Health care occupations
    • Health sciences
    • Human pregnancy
  • Hobbies
    • Entertainment
    • Environmental design
    • Handicrafts
    • Hobbies
    • Home appliances
    • Home improvement
    • Horticulture and gardening
  • Learn & Earn
  • Learners Hub
    • NFT Beginners
  • Movie
  • Music
    • Musical instruments
  • News
    • Nation Wants to Know
    • National News
  • Personal Development
    • Marriage
    • Parenting
    • Personal care and service occupations
    • Personal development
    • Personal life
  • Real Estate
  • Religion
    • Prayer Method
    • Puran
    • Sanatan Dharma Basic
    • Sanatan Dharma Symbols & meaning
    • Scienfic reason behind Sanatan Dharma
  • Social Media
  • Technology
    • Services & Software
    • Software development
    • Technology News
  • Travel & Tourism
    • Things to Do
    • Travel Blogs

Subscriptions

  • admin

Recent News

  • 52 week high stocks: Stock market update: Stocks that hit 52-week lows on NSE in today’s trade
  • Adani Ports to buy back another ₹2.3k crore of 2024 bond
  • Switzerland of the Northeast, Dima Hasao in Assam, aims to woo tourists | Travel
  • Home
  • Browse
    • Personal Development
    • Fashion & Lifestyle
    • Health & Fitness
    • Cooking & Food
    • Stock Market & Trading
    • Business & Startups
    • Technology
    • Travel & Tourism
    • Business
    • Freelancing
    • Learners Hub
  • Refer & Earn
  • Blogs
No Result
View All Result
  • Login
No Result
View All Result
  • Feedback/Suggestions
  • About Us
  • Contact Us
Home Education Graphics Design Skills

How to Add and Subtract Time From a Date in JavaScript

admin by admin
September 20, 2023
in Graphics Design Skills
0 0
0
US’ PVH Corp announces revenue increase of 4% to $2.207 bn in Q2 FY23
0
SHARES
27
VIEWS
Share on FacebookShare on Twitter

In this post, we’ll discuss how you can manipulate the date with a JavaScript Date object. Specifically, we’ll see how you can add time to a Date object and subtract time from a Date object in JavaScript.

Often, you’ll need to work with dates and times in JavaScript. Luckily, JavaScript provides a built-in Date object which provides a lot of utility methods for date and time management. Although these methods are really useful for retrieving different elements of the date and time, a Date object doesn’t provide any methods that you can use to manipulate the date itself. In most cases, you can just use these methods to format the date and time for output.

In fact, if you want to perform operations on a Date object like adding time to or subtracting time from a date, there’s no easy way in vanilla JavaScript. Often, you’ll just end up implementing a custom solution which works for you. Alternately, you can use a date and time library like moment.js. Today, we’re going to discuss both ways of performing date manipulations in JavaScript.

How to Add Time to a JavaScript Date With Vanilla JavaScript

In this section, we’ll discuss how you can add time to a JavaScript Date object in vanilla JavaScript.

In JavaScript, the getTime() function returns the number of milliseconds since the Unix epoch time. That’s just a computer time convention that counts the number of seconds (milliseconds in JavaScript) since midnight UTC on January 1st, 1970.

Let’s try to understand how you can use the getTime() function to add time to a Date object in JavaScript. In the following example, we’ll add one hour to the existing Date object.

1
var currentDateObj = new Date();
2
var numberOfMlSeconds = currentDateObj.getTime();
3
var addMlSeconds = 60 * 60 * 1000;
4
var newDateObj = new Date(numberOfMlSeconds + addMlSeconds);

Firstly, we’ve initialized the currentDateObj variable with the current date, and it’s a Date object. Next, we’ve used the getTime() function to get the number of milliseconds from the currentDateObj object.

Next, we’ve calculated the number of milliseconds in an hour. Basically, we’ve just multiplied the number of minutes in an hour (60) by the number of seconds in a minute (60) by the number of milliseconds in a second (1000) to get the number of milliseconds in an hour.

As you might already know, you can initialize a Date object by providing the number of milliseconds as the first argument, and this would initialize a date object in reference to it. Thus, we’ve added numberOfMlSeconds and addMlSeconds to get the total number of milliseconds, and we’ve used it to initialize a new date object. And the end result is the newDateObj object, which should show a date ahead by one hour compared to the currentDateObj object.

In fact, you can go ahead and make a reusable function, as shown in the following snippet.

1
function addHoursToDate(objDate, intHours) {
2
    var numberOfMlSeconds = objDate;
3
    var addMlSeconds = (intHours * 60) * 60 * 1000;
4
    var newDateObj = new Date(numberOfMlSeconds + addMlSeconds);
5

6
    return newDateObj;
7
}

Here’s how you can call it to get, for example, a date exactly one day in the future.

1
addHoursToDate(Date.now(), 24)

Date.now() already returns milliseconds, so no need to use getTime() in this scenario.

Try altering the hours value in the JavaScript panel below. Watch as the date outputted to the HTML tab changes.

You can also use the above function to add a number of days to an existing Date object; you just need to convert days to hours before calling the above function.

How to Subtract Time From a JavaScript Date With Vanilla JavaScript

In this section, we’ll see how you can subtract time from a JavaScript Date object.

The logic of subtracting time from a Date object is very similar to the add operation, except that we need to subtract milliseconds instead of adding them.

Let’s go through the following example to see how it works.

1
function subtractTimeFromDate(objDate, intHours) {
2
    var numberOfMlSeconds = objDate;
3
    var addMlSeconds = (intHours * 60) * 60 * 1000;
4
    var newDateObj = new Date(numberOfMlSeconds - addMlSeconds);
5

6
    return newDateObj;
7
}

As you can see, it’s almost identical to the add operation. The only difference is that we’re subtracting addMlSeconds from numberOfMlSeconds instead of adding.

How to Use the Moment.js Library to Perform Date Manipulations

In the previous section, we discussed how you can use vanilla JavaScript to perform date and time manipulations. If you don’t require any complex operations with a JavaScript Date object, you can live with vanilla JavaScript implementation. On the other hand, if your project requires you to perform different types of date and time manipulations, it’s better to use a third-party library which can make things easier for you.

Date and time can be surprisingly complicated. For example, think about adding a number of years to a date using the method above. It would be easy, if years were always the same length. However, in the real world, we have leap years. Similarly, if you want to add a number of months to a date, you’ll have to know how many days each month has. 

In this section, we’ll see how you can use the Moment.js library, which provides a plethora of utility methods to manipulate a JavaScript Date object. Go ahead and download the Moment.js library, and you’re ready to use it!

With the Moment.js library you just need to call the moment() function to get the current date object. Once you get it, you can use different parsing methods for formatting and manipulation methods for manipulating the current date object.

1
// display the current datetime
2
console.log(moment().format());
3

4
// add '1' hour to the current datetime
5
console.log(moment().add(1, 'h').format());
6

7
// add '30' minutes to the current datetime
8
console.log(moment().add(30, 'm').format());
9

10
// add '2' days to the current datetime
11
console.log(moment().add(2, 'd').format());
12

13
// add '1' week to the current datetime
14
console.log(moment().add(1, 'w').format());
15

16
// add '1' month to the current datetime
17
console.log(moment().add(1, 'M').format());
18

19
// subtract '1' hour from the current datetime
20
console.log(moment().subtract(1, 'h').format());
21

22
// subtract '30' minutes from the current datetime
23
console.log(moment().subtract(30, 'm').format());
24

25
// subtract '1' day from the current datetime
26
console.log(moment().subtract(1, 'd').format());
27

28
// subtract '1' week from the current datetime
29
console.log(moment().subtract(1, 'w').format());
30

31
// subtract '3' months from the current datetime
32
console.log(moment().subtract(3, 'M').format());

You can use the CodePen below to experiment with different Moment utility methods and ways of adding or subtracting dates. For more information, I recommend you visit the official documentation.

So that’s how you can use the Moment.js library for formatting and manipulating dates.

Conclusion

Today, we discussed how you can perform date manipulations with a JavaScript Date object. Apart from vanilla JavaScript, we also explored the Moment.js library, which provides fairly easy ways to perform date manipulations.



Source link

Tags: AddDateJavaScriptsubtracttime

Latest News

  • Trending
  • Comments
  • Latest
Cryptocurrencies With Incredibly High Market Caps

Iravin Nizhal Box Office Collection Day 3 Worldwide & Budget

July 17, 2022
Indian-Origin Leader Is New Singapore President

Indian-Origin Leader Is New Singapore President

September 1, 2023
17-Year-Old High School Basketball Player In US Dies After Collapsing On Court

17-Year-Old High School Basketball Player In US Dies After Collapsing On Court

August 12, 2023
Celebrity couple Riteish Deshmukh, Genelia D’Souza buys BMW iX electric SUV worth Rs 1.16 crore | Electric Vehicles News

Celebrity couple Riteish Deshmukh, Genelia D’Souza buys BMW iX electric SUV worth Rs 1.16 crore | Electric Vehicles News

September 1, 2022
Bitcoin Could Collapse Another 50%, Says Michael “Big Short” Burry

Bitcoin Could Collapse Another 50%, Says Michael “Big Short” Burry

0
Crypto Market Loses $60 Billion As Bitcoin Dips Below $20,000

Crypto Market Loses $60 Billion As Bitcoin Dips Below $20,000

0
Bitcoin Sees Worst Quarter In 11 Years

Bitcoin Sees Worst Quarter In 11 Years

0
Ethereum (ETH) Bends Toward $1,000 As Doubt Fills Crypto Markets

Ethereum (ETH) Bends Toward $1,000 As Doubt Fills Crypto Markets

0
52 week high stocks: Stock market update: Stocks that hit 52-week lows on NSE in today’s trade

52 week high stocks: Stock market update: Stocks that hit 52-week lows on NSE in today’s trade

September 27, 2023
Adani Ports to buy back another ₹2.3k crore of 2024 bond

Adani Ports to buy back another ₹2.3k crore of 2024 bond

September 27, 2023

Switzerland of the Northeast, Dima Hasao in Assam, aims to woo tourists | Travel

September 27, 2023
Modi: Opposition stalled women’s quota bill for three decades: PM Modi | India News

Modi: Opposition stalled women’s quota bill for three decades: PM Modi | India News

September 27, 2023
Moneyhaat News

Money Haat

You finally have someone to confide in about money. Get financial clarity as we uncover your values, spot barriers, and set achievable goals.

  • Feedback/Suggestions
  • About Us
  • Contact Us

© 2022 Money Haat - Designed By JSD Solutions.

No Result
View All Result
  • Home
  • Browse
    • Personal Development
    • Fashion & Lifestyle
    • Health & Fitness
    • Cooking & Food
    • Stock Market & Trading
    • Business & Startups
    • Technology
    • Travel & Tourism
    • Business
    • Freelancing
    • Learners Hub
  • Refer & Earn
  • Blogs

© 2022 Money Haat - Designed By JSD Solutions.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In

Add New Playlist

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?