【问题标题】:How can i calculate the remaining time of the current date with the created date?如何计算当前日期与创建日期的剩余时间?
【发布时间】:2020-10-09 08:03:57
【问题描述】:

我需要计算到未来某个时间点的剩余时间。我正在使用new Date() 获取当前日期,例如:

Fri Oct 09 2020 09:59:21 GMT+0200 (Central European Summer Time)

我怎样才能计算到对象中的这个时间的剩余时间:

{
   appointment_date: "Tue Oct 20 2020"
   appointment_hour: "08:00 - 09:00"
}

我想以月、周、日等为单位显示。如果为零,则应省略。

【问题讨论】:

    标签: javascript momentjs


    【解决方案1】:

    您可以为此使用moment.duration()

    const appointment = {
      appointment_date: "Tue Oct 20 2020",
      appointment_hour: "08:00 - 09:00"
    };
    
    const appointmentString = appointment.appointment_date + " " + appointment.appointment_hour.split(' - ')[0];
    const difference = moment.duration(
      moment(appointmentString, "ddd MMM DD YYYY HH:mm").diff(moment()));
    
    const result = [];
    
    const units = [
      "months",
      "weeks",
      "days",
      "hours",
      "minutes",
      "seconds"
    ];
    
    units.forEach(function(unit) {
      // This is equal to difference.months() > 0, difference.weeks() > 0, etc
      if (difference[unit]() > 0) {
        result.push(difference[unit]() + " " + unit);
      }
    });
    
    console.log(result.join(', '));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

    【讨论】:

    • 感谢鲁本的回复
    【解决方案2】:

    如果你想要纯 JavaScript 的解决方案,试试这个

    const appointment = {
      appointment_date: "Tue Oct 20 2020",
      appointment_hour: "08:00 - 09:00"
    };
    
    const result = [];
    var curr = new Date().getTime();
    var appo = new Date(appointment.appointment_date).getTime() + parseInt(appointment.appointment_hour.split(' - ')[0]) *60 *60 *1000;
    
    function dhm(t){
        var cd = 24 * 60 * 60 * 1000,
            ch = 60 * 60 * 1000,
            d = Math.floor(t / cd),
            h = Math.floor( (t - d * cd) / ch),
            m = Math.round( (t - d * cd - h * ch) / 60000);
      if( m === 60 ){
        h++;
        m = 0;
      }
      if( h === 24 ){
        d++;
        h = 0;
      }
      return [d, h, m].join(':');
    }
    console.log(appo - curr)
    console.log( dhm( appo - curr ) );
    

    【讨论】:

      猜你喜欢
      • 2014-10-18
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多