Open In App

How To Set Time With Date in Moment.js?

Last Updated : 23 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Moment.js is a powerful JavaScript library that makes it easy to work with dates and times. Sometimes, we want to set a specific time to an already existing date. For example- we have a date like "2024-08-15" and we want to set the time to "9:00 AM". Moment.js provides simple ways to do this.

In this article, we are going to discuss different approaches to set time along with a date in Moment.js.

Below are different approaches using which we can set time with a date in Moment.js:

Approach 1: Using the set() method

The set() method allows us to set specific time components (like hours, minutes, seconds, and milliseconds) simultaneously. We provide the values we want to set, and it returns a new Moment.js object with the updated time.

Example:

JavaScript
// Importing the moment library
const moment = require('moment');

const dateWithTime = moment('2024-08-15').
    set({ hour: 10, minute: 30, second: 0, millisecond: 0 });
console.log(dateWithTime.format('YYYY-MM-DD HH:mm:ss')); 

Output

set-me
Using the set() method

Approach 2: Using different time methods of the Moment.js library

These are the hours(), minutes(), seconds(), and milliseconds() methods let us set each part of the time separately. This approach is handy when we need to update only one or two time elements.

Example:

JavaScript
// Importing the moment library
const moment = require('moment');

const dateWithTime = moment('2024-08-15').hours(10).
    minutes(30).seconds(0).milliseconds(0);
console.log(dateWithTime.format('YYYY-MM-DD HH:mm:ss')); 

Output

hr-min-sec-me
Using different time methods of the Moment.js library

Approach 3: Using the format() method

The format() method is typically used to display dates, but we can also use it to create a Moment.js object that includes both a date and time by passing a string with the desired format.

Example

JavaScript
const moment = require('moment');

const dateWithTime = moment('2024-08-15 10:30:00');
console.log(dateWithTime.format('YYYY-MM-DD HH:mm:ss')); 


Output

format-meth
Using the format() method

Next Article

Similar Reads

  翻译: