1

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

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

// 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);
4

2 回答 2

5

演示

只需从退货中删除您不想看到的内容。现在您可以简单地传入日期对象,您不必费心进行转换。

var cc = new Date("9/13/2012 12:00 AM");
var c = new Date();

function timeDifference(d, dd) {
    var minute = 60 * 1000,
        hour = minute * 60,
        day = hour * 24,
        month = day * 30,
        ms = Math.abs(d - dd);

    var months = parseInt(ms / month, 10);

        ms -= months * month;

    var days = parseInt(ms / day, 10);

        ms -= days * day;

    var hours = parseInt(ms / hour, 10);

        ms -= hours * hour;
    var minutes = parseInt(ms / minute, 10);

    return [
        months + " months",
        days + " days",
        hours + " hours",
        minutes + " minutes"
    ].join(", ");
};

document.body.innerHTML += timeDifference(cc, c) + "<br />";
于 2013-05-20T13:09:02.237 回答
5
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
于 2013-05-20T13:43:53.087 回答