How to convert hours and minutes to minutes with moment.js?

I need to convert hours and minutes in minutes values. With pure JavaScript Date object I do the following:

var d = new Date();
var minutes = d.getHours() * 60 + d.getMinutes();

I’ve just switched to moment.js and looking for better solution likes the following:

var minutes = moment(new Date()).toMinutes()

Is there is something like this?

I think your best bet is to create a Duration and then get the minutes using asMinutes. This is probably clearer when describing an interval of time.

moment.duration().asMinutes()

Here is the reference in the docs.

For those seeking to get minutes from an existing Moment object, you can first format it to whatever you need, then use duration to get its duration in minutes:

moment.duration(myMomentObjectToConvert.format("HH:mm")).asMinutes()

You could use:

var m = moment(new Date());
var minutes = (m.hour()*60) + m.minute();

http://momentjs.com/docs/#/get-set/minute/

I didn’t needed moment.js, at least worked for my scenarios:

console.log('converting 2 hours, 20 minutes and 120 seconds to minutes');

var hours = 2,
  minutes = 20,
  seconds = 120,
  timeInminutes = (hours * 60) + minutes + (seconds / 60);

console.log('2 hours, 20 minutes and 120 seconds to minutes is', timeInminutes, ' minutes')

const moment = require('moment')
var date = new Date()
console.log(date) // 2018-11-09T10:01:33.131Z

// 1.
console.log( 'object', moment(new Date()).toObject() )
// { years: 2018,
// months: 10,
// date: 9,
// hours: 13,
// minutes: 1,
// seconds: 33,
// milliseconds: 135 }

// 2.
console.log( 'array', moment(new Date()).toArray() ) // array [ 2018, 10, 9, 13, 1, 33, 141 ]

// 3.
console.log( 'year', moment(new Date()).toObject().years ) // year 2018
console.log( 'day of month', moment(new Date()).toObject().date ) // day of month 9
console.log( 'hours', moment(new Date()).toObject().hours ) // hours 13
console.log( 'minutes', moment(new Date()).toObject().minutes ) // minutes 1
console.log( 'seconds', moment(new Date()).toObject().seconds ) // seconds 33
console.log( 'milliseconds', moment(new Date()).toObject().milliseconds ) // milliseconds 139

// 4.
console.log( 'weeks', moment(new Date()).weeks() ) // weeks 45
console.log( 'day of week', moment(new Date()).days() ) // day of week 5
console.log( 'day of month', moment(new Date()).date() ) // day of month 9
console.log( 'hours', moment(new Date()).hours() ) // hours 13
console.log( 'minutes', moment(new Date()).minutes() ) // minutes 1
console.log( 'seconds', moment(new Date()).seconds() ) // seconds 33
console.log( 'milliseconds', moment(new Date()).milliseconds() ) // milliseconds 141


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts