문제

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

just for simplification -- '07:07:00' is in HH:mm:ss format and this will be converted in minutes

moment.duration('07:07:00').asMinutes()

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top