本文介绍了javascript - 两次之间经过的分钟数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序需要两次之间经过的分钟数。
例如:9:00到10:00是60分钟。这是我解决的解决方案,
,但似乎过于冗长。我可以做得更好吗?

I have an application that requires the elapsed minutes between two times.Eg: 9:00 to 10:00 is sixty minutes. This is the solution that I worked out,but it seems excessively verbose. Can I do better?

编辑:我从远程系统接收格式为YYYYMMDD和HHMM或HMM的字符串。

I receive strings in the format of YYYYMMDD and HHMM or HMM from a remote system.

// define a start time and end time as string
var start_time ="830";
var end_time ="1930";

// make sure we have complete 4 digit time
start_time   = ('0' + start_time).slice(-4);
end_time     = ('0' + end_time).slice(-4);

// extract start minutes and seconds
start_hour = start_time.substring(0,2);
start_minute = start_time.substring(2,4);

// extract end minutes and seconds
end_hour = end_time.substring(0,2);
end_minute = end_time.substring(2,4);

//get current date - it seems that we need a date a valid date to create a Date object
var now = new Date();
var year = now.getUTCFullYear();
var month = now.getUTCMonth();
var day = now.getDate();

// create Date object
var start_date_time_object = new Date(year,month,day,start_hour,start_minute);
var end_date_time_object = new Date(year,month,day,end_hour,end_minute);

// get number of minutes between start and end times
var start_minutes = (start_date_time_object.getHours() * 60) +  start_date_time_object.getMinutes();
var end_minutes = (end_date_time_object.getHours() * 60) +  end_date_time_object.getMinutes();

// calculate net time elapsed
var duration = end_minutes - start_minutes;

// display
console.log(start_minutes);
console.log(end_minutes);
console.log(duration);


推荐答案

var start_time ="830";
var end_time ="1930";

var start_hour = start_time.slice(0, -2);
var start_minutes = start_time.slice(-2);

var end_hour = end_time.slice(0, -2);
var end_minutes = end_time.slice(-2);

var startDate = new Date(0,0,0,start_hour, start_minutes);
var endDate = new Date(0,0,0,end_hour, end_minutes);

var millis = endDate - startDate;
var minutes = millis/1000/60;
alert(minutes);

--output:--
660

这篇关于javascript - 两次之间经过的分钟数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 09:21