簡體   English   中英

使用矩JS計算確切的時差

[英]Calculate the exact time difference using moment JS

我需要使用矩JS計算確切的時間差。

我的JS代碼是:

var a = moment(from_url);
                a.format('DD/MM/YYYY hh:mm:ss');
                var b = moment(to_url);
                b.format('DD/MM/YYYY hh:mm:ss');

                console.log("from URL")
                var from_hours = from_url()
                console.log(b.diff(a, 'minutes')) // 
                console.log(b.diff(a, 'hours')) // 
                console.log(b.diff(a, 'days')) // 
                console.log(b.diff(a, 'weeks')) // 

                console.log("Time interval: "+b.diff(a, 'days')+ " days "+ b.diff(a, 'hours') +" hours " +b.diff(a, 'minutes')+" mintes");

現在,

from_url = '2016-05-03T08:00:00';
to_url = '2016-05-04T09:00:00';

現在,對於這些時間,我得到的輸出為: Time interval: 1 days 25 hours 1500 minutes將所有內容轉換為天(1天〜25小時)。

但是, 我想要的輸出是:1天1小時0分鍾

有人可以幫我嗎? 我是JS的新手,無法弄清楚。 謝謝。

要解析字符串,您應該始終告訴解析器您提供的格式。 Moment.js可以提供幫助,但是您也可以使用自己的小函數。

要獲得天,小時等的差異,您可以簡單地從另一個日期減去一個日期以獲取毫秒,然后將其轉換為所需的格式。

請注意,日期算術並不簡單,有許多規則會根據自定義或管理規則而更改。 此外,在超過夏令時時限,有些日子會長達23小時,而有些日子會長達25小時。

以下是一種不考慮夏令時的簡單方法。 希望注釋足夠,請使用輸出格式來獲取所需的內容。

 // Parse ISO format string as local, ignore timezone // Eg 2016-05-29T23:32:15 function parseISOLocal(s) { // Split string into its parts var b = s.split(/\\D/); // Create and return a date object return new Date(b[0], b[1]-1, b[2], b[3], b[4], b[5]); } // Convert a millisecond value to days, hours, minutes and seconds function formatDHMS(ms) { // Helper to add 's' to a number if other than 1 function addS(n){return n == 1? '' : 's';} // Get the whole values of each unit, rounded down ( |0 truncates) var d = ms/8.64e7 | 0; // days var h = (ms%8.64e7) / 3.6e6 | 0; // hours var m = (ms%3.6e6) / 6e4 | 0; // minutes var s = (ms%6e4) / 1e3 | 0; // seconds // Return a formatted string return d + ' day' + addS(d) + ', ' + h + ' hour' + addS(h) + ', ' + m + ' minute' + addS(m) + ' and ' + s + ' second' + addS(s); } document.write(formatDHMS(parseISOLocal('2016-05-04T09:00:00') - parseISOLocal('2016-05-03T08:00:00'))) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM