Javascript返回两个日期之间的天数,小时数,分钟数,秒数

时间:2012-12-16 17:48:57

标签: javascript datetime

有没有人可以将我链接到一些教程,在那里我可以找到如何在2个unix日期之间返回javascript中的天,小时,分钟,秒?

我有:

var date_now = unixtimestamp;
var date_future = unixtimestamp;

我想返回(直播)从date_now到date_future的剩余天数,小时数,分钟数,秒数。

21 个答案:

答案 0 :(得分:128)

只需计算出以秒为单位的差异(不要忘记JS时间戳实际上以毫秒为单位)并分解该值:

// get total seconds between the times
var delta = Math.abs(date_future - date_now) / 1000;

// calculate (and subtract) whole days
var days = Math.floor(delta / 86400);
delta -= days * 86400;

// calculate (and subtract) whole hours
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;

// calculate (and subtract) whole minutes
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;

// what's left is seconds
var seconds = delta % 60;  // in theory the modulus is not required

编辑代码已调整,因为我刚刚意识到原始代码返回了总小时数等,而不是整天计算后剩余的小时数。

答案 1 :(得分:28)

这里是javascript :(例如,未来的日期是新年)

DEMO (每秒更新一次)

var dateFuture = new Date(new Date().getFullYear() +1, 0, 1);
var dateNow = new Date();

var seconds = Math.floor((dateFuture - (dateNow))/1000);
var minutes = Math.floor(seconds/60);
var hours = Math.floor(minutes/60);
var days = Math.floor(hours/24);

hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);

答案 2 :(得分:22)

我把它称为"雪人卡尔☃方法"当你需要额外的时间跨度时,我认为它会更灵活一些,例如周,飞蛾,几年,几个世纪...... 并且不需要太多的重复代码:

var d = Math.abs(date_future - date_now) / 1000;                           // delta
var r = {};                                                                // result
var s = {                                                                  // structure
    year: 31536000,
    month: 2592000,
    week: 604800, // uncomment row to ignore
    day: 86400,   // feel free to add your own row
    hour: 3600,
    minute: 60,
    second: 1
};

Object.keys(s).forEach(function(key){
    r[key] = Math.floor(d / s[key]);
    d -= r[key] * s[key];
});

// for example: {year:0,month:0,week:1,day:2,hour:34,minute:56,second:7}
console.log(r);

有一个 FIDDLE / ES6 Version (2018) / {{3} }

受到TypeScript Version (2019)答案的启发。

答案 3 :(得分:8)

请注意,仅根据差异计算不会涵盖所有情况:闰年和“夏令时”的转换。

Javascript内置库很差,无法使用日期。我建议你使用第三方javascript库,例如MomentJS;你可以看到here你正在寻找的功能。

答案 4 :(得分:3)

我知道持续时间细分的最佳图书馆是countdown.js。它处理所有困难情况,如闰年和夏令时为csg mentioned,甚至允许您指定模糊概念,如月和周。以下是您案例的代码:

//assuming these are in *seconds* (in case of MS don't multiply by 1000 below)
var date_now = 1218374; 
var date_future = 29384744;

diff = countdown(date_now * 1000, date_future * 1000, 
            countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS);
alert("days: " + diff.days + " hours: " + diff.hours + 
      " minutes: " + diff.minutes + " seconds: " + diff.seconds);

//or even better
alert(diff.toString()); 

这是一个JSFiddle,但它可能仅适用于禁用了网络安全的FireFox或Chrome,因为countdown.js托管的是 text / plain MIME类型(你'应该服务该文件,而不是链接到countdownjs.org)。

答案 5 :(得分:1)

对于那些只想要几小时和几分钟的人来说,使用这个

const oldDate = new Date("2021-04-28T13:17:31.000Z")
const newDate = new Date("2021-04-28T22:08:07.000Z")
const msToTime = (ms) => ({
    hours: Math.trunc(ms/3600000),
    minutes: Math.trunc((ms/3600000 - Math.trunc(ms/3600000))*60) + ((ms/3600000 - Math.trunc(ms/3600000))*60 % 1 != 0 ? 1 : 0)
})

console.log(msToTime(Math.abs(newDate-oldDate)))

答案 6 :(得分:1)

function calculateExamRemainingTime(exam_end_at) {

$(function(){

    const calcNewYear = setInterval(function(){

        const exam_ending_at    = new Date(exam_end_at);
        const current_time      = new Date();
       
        const totalSeconds     = Math.floor((exam_ending_at - (current_time))/1000);;
        const totalMinutes     = Math.floor(totalSeconds/60);
        const totalHours       = Math.floor(totalMinutes/60);
        const totalDays        = Math.floor(totalHours/24);

        const hours   = totalHours - ( totalDays * 24 );
        const minutes = totalMinutes - ( totalDays * 24 * 60 ) - ( hours * 60 );
        const seconds = totalSeconds - ( totalDays * 24 * 60 * 60 ) - ( hours * 60 * 60 ) - ( minutes * 60 );

        const examRemainingHoursSection = document.querySelector('#remainingHours');
        const examRemainingMinutesSection = document.querySelector('#remainingMinutes');
        const examRemainingSecondsSection = document.querySelector('#remainingSeconds');

        examRemainingHoursSection.innerHTML = hours.toString();
        examRemainingMinutesSection.innerHTML = minutes.toString();
        examRemainingSecondsSection.innerHTML = seconds.toString();

    },1000);
});
}

calculateExamRemainingTime('2025-06-03 20:20:20');

答案 7 :(得分:1)

简便方式

function diff_hours(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  diff /= (60 * 60);
  return Math.abs(Math.round(diff));

 }


function diff_minutes(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  diff /= (60);
  return Math.abs(Math.round(diff));

 }

function diff_seconds(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  return Math.abs(Math.round(diff));

 }

function diff_miliseconds(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime());
  return Math.abs(Math.round(diff));

 }


dt1 = new Date(2014,10,2);
dt2 = new Date(2014,10,3);
console.log(diff_hours(dt1, dt2));


dt1 = new Date("October 13, 2014 08:11:00");
dt2 = new Date("October 14, 2014 11:13:00");
console.log(diff_hours(dt1, dt2));

console.log(diff_minutes(dt1, dt2));

console.log(diff_seconds(dt1, dt2));

console.log(diff_miliseconds(dt1, dt2));

答案 8 :(得分:1)

使用moment.js库,例如:

var time = date_future - date_now;
var seconds = moment.duration(time).seconds();
var minutes = moment.duration(time).minutes();
var hours   = moment.duration(time).hours();
var days    = moment.duration(time).days();

答案 9 :(得分:1)

这是一个代码示例。我使用简单的计算而不是使用预先计算,如1天是86400秒。因此,您可以轻松地遵循逻辑。

// Calculate time between two dates:
var date1 = new Date('1110-01-01 11:10');
var date2 = new Date();

console.log('difference in ms', date1 - date2);

// Use Math.abs() so the order of the dates can be ignored and you won't
// end up with negative numbers when date1 is before date2.
console.log('difference in ms abs', Math.abs(date1 - date2));
console.log('difference in seconds', Math.abs(date1 - date2) / 1000);

var diffInSeconds = Math.abs(date1 - date2) / 1000;
var days = Math.floor(diffInSeconds / 60 / 60 / 24);
var hours = Math.floor(diffInSeconds / 60 / 60 % 24);
var minutes = Math.floor(diffInSeconds / 60 % 60);
var seconds = Math.floor(diffInSeconds % 60);
var milliseconds = Math.round((diffInSeconds - Math.floor(diffInSeconds)) * 1000);

console.log('days', days);
console.log('hours', ('0' + hours).slice(-2));
console.log('minutes', ('0' + minutes).slice(-2));
console.log('seconds', ('0' + seconds).slice(-2));
console.log('milliseconds', ('00' + milliseconds).slice(-3));

答案 10 :(得分:1)

function update(datetime = "2017-01-01 05:11:58") {
    var theevent = new Date(datetime);
    now = new Date();
    var sec_num = (theevent - now) / 1000;
    var days    = Math.floor(sec_num / (3600 * 24));
    var hours   = Math.floor((sec_num - (days * (3600 * 24)))/3600);
    var minutes = Math.floor((sec_num - (days * (3600 * 24)) - (hours * 3600)) / 60);
    var seconds = Math.floor(sec_num - (days * (3600 * 24)) - (hours * 3600) - (minutes * 60));

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}

    return  days+':'+ hours+':'+minutes+':'+seconds;
}

答案 11 :(得分:0)

let delta = Math.floor(Math.abs(start.getTime() - end.getTime()) / 1000);
let hours = Math.floor(delta / 3600);
delta -= hours * 3600;
let minutes = Math.floor(delta / 60);
delta -= minutes * 60;
let seconds = delta;
if (hours.toString().length === 1) {
  hours = `0${hours}`;
}
if (minutes.toString().length === 1) {
  minutes = `0${minutes}`;
}
if (seconds.toString().length === 1) {
  seconds = `0${seconds}`;
}
const recordingTime = `${hours}:${minutes}:${seconds}`;

答案 12 :(得分:0)

简短而灵活,支持负值,尽管使用了两个逗号表达式:)

function timeUnitsBetween(startDate, endDate) {
  let delta = Math.abs(endDate - startDate) / 1000;
  const isNegative = startDate > endDate ? -1 : 1;
  return [
    ['days', 24 * 60 * 60],
    ['hours', 60 * 60],
    ['minutes', 60],
    ['seconds', 1]
  ].reduce((acc, [key, value]) => (acc[key] = Math.floor(delta / value) * isNegative, delta -= acc[key] * isNegative * value, acc), {});
}

示例:

timeUnitsBetween(new Date("2019-02-11T02:12:03+00:00"), new Date("2019-02-11T01:00:00+00:00"));
// { days: -0, hours: -1, minutes: -12, seconds: -3 }

受到RienNeVaPlu͢s解决方案的启发。

答案 13 :(得分:0)

MomentJS具有执行此操作的功能:

const start = moment(j.timings.start);
const end = moment(j.timings.end);
const elapsedMinutes = end.diff(start, "minutes");

答案 14 :(得分:0)

我的解决方案还不那么清楚,但我将其作为另一个示例

console.log(duration('2019-07-17T18:35:25.235Z', '2019-07-20T00:37:28.839Z'));

function duration(t0, t1){
    let d = (new Date(t1)) - (new Date(t0));
    let weekdays     = Math.floor(d/1000/60/60/24/7);
    let days         = Math.floor(d/1000/60/60/24 - weekdays*7);
    let hours        = Math.floor(d/1000/60/60    - weekdays*7*24            - days*24);
    let minutes      = Math.floor(d/1000/60       - weekdays*7*24*60         - days*24*60         - hours*60);
    let seconds      = Math.floor(d/1000          - weekdays*7*24*60*60      - days*24*60*60      - hours*60*60      - minutes*60);
    let milliseconds = Math.floor(d               - weekdays*7*24*60*60*1000 - days*24*60*60*1000 - hours*60*60*1000 - minutes*60*1000 - seconds*1000);
    let t = {};
    ['weekdays', 'days', 'hours', 'minutes', 'seconds', 'milliseconds'].forEach(q=>{ if (eval(q)>0) { t[q] = eval(q); } });
    return t;
}

答案 15 :(得分:0)

这是我的看法:

timeSince(123456) => "1 day, 10 hours, 17 minutes, 36 seconds"

和代码:

function timeSince(date, longText) {
    let seconds = null;
    let leadingText = null;

    if (date instanceof Date) {
        seconds = Math.floor((new Date() - date) / 1000);
        if (seconds < 0) {
            leadingText = " from now";
        } else {
            leadingText = " ago";
        }
        seconds = Math.abs(seconds);
    } else {
        seconds = date;
        leadingText = "";
    }

    const intervals = [
        [31536000, "year"  ],
        [ 2592000, "month" ],
        [   86400, "day"   ],
        [    3600, "hour"  ],
        [      60, "minute"],
        [       1, "second"],
    ];

    let interval = seconds;
    let intervalStrings = [];
    for (let i = 0; i < intervals.length; i++) {
        let divResult = Math.floor(interval / intervals[i][0]);
        if (divResult > 0) {
            intervalStrings.push(divResult + " " + intervals[i][1] + ((divResult > 1) ? "s" : ""));
            interval = interval % intervals[i][0];
            if (!longText) {
                break;
            }
        }
    }
    let intStr = intervalStrings.join(", ");

    return intStr + leadingText;
}

答案 16 :(得分:0)

这是一个代码,用于查找天,小时,分钟,秒中两个日期之间的差异(假设未来日期是新年日期)。

var one_day = 24*60*60*1000;              // total milliseconds in one day

var today = new Date();
var new_year = new Date("01/01/2017");    // future date

var today_time = today.getTime();         // time in miliiseconds
var new_year_time = new_year.getTime();                         

var time_diff = Math.abs(new_year_time - today_time);  //time diff in ms  
var days = Math.floor(time_diff / one_day);            // no of days

var remaining_time = time_diff - (days*one_day);      // remaining ms  

var hours = Math.floor(remaining_time/(60*60*1000));   
remaining_time = remaining_time - (hours*60*60*1000);  

var minutes = Math.floor(remaining_time/(60*1000));        
remaining_time = remaining_time - (minutes * 60 * 1000);   

var seconds = Math.ceil(remaining_time / 1000);   

答案 17 :(得分:0)

我们可以通过简单的方法来实现

/*Declare the function */
function Clock(){
    let d1 = new Date("1 Jan 2021");
    let d2 = new Date();

    let difference = Math.abs(d1 - d2); //to get absolute value
    //calculate for each one
    let Days = Math.floor(difference / ( 1000 * 60 * 60 * 24 ));
    let Hours = Math.floor((difference / ( 1000 * 60 * 60 )) % 24);
    let Mins = Math.floor((difference / ( 1000 * 60 )) % 60);
    let Seconds = Math.floor((difference / ( 1000 )) % 60);

    //getting nodes and change the text inside
    let getday = document.querySelector(".big_text_days");
    let gethour = document.querySelector(".big_text_hours");
    let getmins = document.querySelector(".big_text_mins");
    let getsec = document.querySelector(".big_text_sec");

    getday.textContent = Check_Zero(Days); 
    gethour.textContent = Check_Zero(Hours);
    getmins.textContent = Check_Zero(Mins)
    getsec.textContent = Check_Zero(Seconds);
}

//call the funcion for every 1 second
setInterval(Clock , 1000);


//check and add zero in front, if it is lessthan 10
function Check_Zero(mytime){
    return mytime < 10 ? "0"+mytime : mytime;

}
*{
    padding: 0px;
    margin: 0px;
    box-sizing: border-box;
}
body{
    max-width: 900px;
    margin: 0px auto;
    background-color:whitesmoke;
    background-size: cover;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 5rem;
}
.main_container{
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}
h1{
    font-size: 3rem;
    color: #3D4B72;
}
.big_text_days , .big_text_hours , .big_text_mins , .big_text_sec{
    font-size: 2rem;
    font-weight: bold;
    line-height: 2;
    color: #AC7591;
    text-align: center;
}
p{
    padding: 20px 0px 20px 0px;
    font-size: 3rem;
    text-align: center;
}
.spantext{
    color: #103c28;
    margin: 0px 3rem;
    font-size: 2rem;
    font-style: italic;
}
.text_sec{
    color : #005259;
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="description" content="Responsive site">
        <meta name="keywords" content="HTML,CSS,JS">
        <meta name="author" content="Ranjan">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>Home</title>

        <link href="https://fonts.googleapis.com/css?family=Alfa+Slab+One|Bree+Serif|Exo|Exo+2|Lato|Mansalva|Playfair+Display&display=swap" rel="stylesheet">
       
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">

</head>

    <body>
        
    <section>
      <h1>CountDown Timer</h1>
        </section>
                
         <section>
          <div class="main_container">
                
            <div class="days_container">
             <p class="big_text_days">1</p>
              <span class="spantext spantextdays">Days</span>
            </div>
    
            <div class="hours_container">
             <p class="big_text_hours">1</p>
              <span class="spantext spantexthours">Hours</span>
            </div>
    
            <div class="mins_container">
             <p class="big_text_mins">1</p>
              <span class="spantext spantextmins">Minutes</span>
            </div>
            
            <div class="sec_container">
             <p class="big_text_sec text_sec">1</p>
              <span class="spantext spantextsec">Seconds</span>
            </div>
         </div>
        </section>

    </body>
</html>

答案 18 :(得分:0)

const arrDiff = [
  {
    label: 'second',
    value: 1000,
  },
  {
    label: 'minute',
    value: 1000 * 60,
  },
  {
    label: 'hour',
    value: 1000 * 60 * 60,
  },
  {
    label: 'day',
    value: 1000 * 60 * 60 * 24,
  },
  {
    label: 'year',
    value: 1000 * 60 * 60 * 24 * 365,
  },
];

function diff(date) {
  let result = { label: '', value: '' };
  const value = Date.now() - date;
  for (let obj of arrDiff) {
    let temp = Math.round(value / obj.value);
    if (temp === 0) {
      break;
    } else
      result = {
        value: temp,
        label: obj.label,
      };
  }
  return result;
}

const postDate = new Date('2020-12-17 23:50:00+0700');
console.log(diff(postDate));

答案 19 :(得分:0)

因为 MomentJS 非常繁重且未经过优化,所以不怕使用模块的人可能应该看看 date-fns,它提供了一个 intervalToDuration 方法,可以执行您想要的操作:

const result = intervalToDuration({
  start: new Date(dateNow),
  end: new Date(dateFuture),
})

这将返回一个看起来像这样的对象:

{
  years: 39,
  months: 2,
  days: 20,
  hours: 7,
  minutes: 5,
  seconds: 0,
}

然后您甚至可以使用 formatDuration 使用您喜欢的参数将此对象显示为字符串

答案 20 :(得分:0)

2021 版

灵感来自Alnitak'sRienNeVaPlus's的答案。

自动计算自和直到(见下面的例子)。

const timeUnits = {
  year: 31536e6,
  month: 2592e6,
  week: 6048e5,
  day: 864e5,
  hour: 36e5,
  minute: 6e4,
  second: 1e3,
};

const timeUnitsNamesShort = {
  year: 'y',
  month: 'm',
  week: 'w',
  day: 'd',
  hour: 'h',
  minute: 'm',
  second: 's',
};

const isFuture = (date) => date > Date.now();

const dateDiffStructure = (date, units = timeUnits) => {
  let delta = Math.abs(date - Date.now());
  return Object.entries(units).reduce((acc, [key, value]) => {
      acc[key] = Math.floor(delta / value);
      delta -= acc[key] * value;
      return acc;
  }, {});
};

const dateDiffStructureToString = (date, diffStructure, values, short) => {
  const diffStructureEntries = values 
    ? Object.entries(diffStructure).filter(([key, value]) => values.includes(key) && value)
    : Object.entries(diffStructure).filter(([, value]) => value);
  if (!diffStructureEntries.length) return 'just now';
  const suffix = isFuture(date) ? 'left' : 'ago';
  const diffString = diffStructureEntries.reduce((acc, [key, value]) => {
      const timeUnit = short
          ? timeUnitsNamesShort[key]
          : value > 1
              ? ` ${key}s`
              : ` ${key}`;
      acc = acc ? `${acc} ` : '';
      return `${acc}${value}${timeUnit}`;
  }, '');
  return `${diffString} ${suffix}`;
};

const getDateDiff = (date, values, short) => {
  const diffStructure = dateDiffStructure(date);
  return dateDiffStructureToString(date, diffStructure, values, short);
};

测试和示例:

const timeUnits = {
  year: 31536e6,
  month: 2592e6,
  week: 6048e5,
  day: 864e5,
  hour: 36e5,
  minute: 6e4,
  second: 1e3,
};

const timeUnitsNamesShort = {
  year: 'y',
  month: 'm',
  week: 'w',
  day: 'd',
  hour: 'h',
  minute: 'm',
  second: 's',
};

const isFuture = (date) => date > Date.now();

const dateDiffStructure = (date, units = timeUnits) => {
  let delta = Math.abs(date - Date.now());
  return Object.entries(units).reduce((acc, [key, value]) => {
    acc[key] = Math.floor(delta / value);
    delta -= acc[key] * value;
    return acc;
  }, {});
};

const dateDiffStructureToString = (date, diffStructure, values, short) => {
  const diffStructureEntries = values ?
    Object.entries(diffStructure).filter(([key, value]) => values.includes(key) && value) :
    Object.entries(diffStructure).filter(([, value]) => value);
  if (!diffStructureEntries.length) return 'just now';
  const suffix = isFuture(date) ? 'left' : 'ago';
  const diffString = diffStructureEntries.reduce((acc, [key, value]) => {
    const timeUnit = short ?
      timeUnitsNamesShort[key] :
      value > 1 ?
      ` ${key}s` :
      ` ${key}`;
    acc = acc ? `${acc} ` : '';
    return `${acc}${value}${timeUnit}`;
  }, '');
  return `${diffString} ${suffix}`;
};

const getDateDiff = (date, values, short) => {
  const diffStructure = dateDiffStructure(date);
  console.log(`dateDiffStructure(${JSON.stringify(date)}) //`, diffStructure);
  return dateDiffStructureToString(date, diffStructure, values, short);
};

const tests = [
  ['After tomorrow', [new Date(Date.now() + 8.64e7 + 1e6)]],
  ['Yesterday', [new Date(Date.now() - 8.64e7)]],
  ['Past', [new Date(Date.now() * Math.random())]],
  ['Future short', [new Date(Date.now() * (Math.random() + 1)), ['year', 'month', 'day'], true]],
  ['Now', [Date.now()]]
];

tests.forEach(([text, args]) => {
  console.log(`${text}:`);
  console.group();
  console.log(`getDateDiff(${args.map(item => JSON.stringify(item)).join(', ')}) //`, getDateDiff(...args));
  console.groupEnd();
});