ArticleZip > Extract Time From Moment Js Object

Extract Time From Moment Js Object

Have you ever found yourself working with dates and times in your web development projects and needed to extract just the time from a Moment.js object? Well, you're in luck because today, we're going to show you how to do just that!

Moment.js is a powerful library that makes working with dates and times in JavaScript a breeze. It provides a ton of handy utilities for parsing, manipulating, and formatting dates and times. However, when you have a Moment.js object representing a specific date and time, you may sometimes want to extract only the time portion of that object.

Thankfully, Moment.js makes it easy to accomplish this task. To extract the time from a Moment.js object, you can use the `format()` method with the `'HH:mm:ss'` format string. This format string tells Moment.js to display the hours, minutes, and seconds components of the time in 24-hour format.

Here's a simple example to illustrate how you can extract the time from a Moment.js object:

Javascript

const moment = require('moment');

const myDateTime = moment('2022-01-01T14:30:00');
const timeOnly = myDateTime.format('HH:mm:ss');

console.log(timeOnly); // Output: 14:30:00

In this example, we first create a Moment.js object `myDateTime` representing the date and time '2022-01-01T14:30:00'. Then, we use the `format()` method with the `'HH:mm:ss'` format string to extract and format only the time portion of the `myDateTime` object.

Remember, the `'HH:mm:ss'` format string specifies that we want to display the hours, minutes, and seconds components of the time. You can customize the format string according to your specific requirements. For example, if you only need the hours and minutes, you can use the `'HH:mm'` format string.

It's important to note that Moment.js objects are mutable, so if you modify a Moment.js object, it will affect the original object. If you need to keep the original object unchanged, you can clone it before extracting the time:

Javascript

const clonedDateTime = myDateTime.clone();
const timeOnly = clonedDateTime.format('HH:mm:ss');

By cloning the `myDateTime` object before extracting the time, you ensure that any operations you perform on `clonedDateTime` will not impact the original `myDateTime` object.

In conclusion, extracting the time from a Moment.js object is a simple task that can be accomplished using the `format()` method with the appropriate format string. Whether you need to display the time in 24-hour format or customize the output to suit your needs, Moment.js provides the flexibility to work with dates and times effortlessly in your web development projects.

×