简体   繁体   English

如何计算当前日期与创建日期的剩余时间?

[英]How can i calculate the remaining time of the current date with the created date?

I need to calculate the remaining time until a certain point in the future.我需要计算到未来某个时间点的剩余时间。 I am using new Date() to get the current date and i am getting for example:我正在使用new Date()来获取当前日期,例如:

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

How can I calculate the remaining time until this time which is in object:我如何计算到此时的剩余时间,即 object:

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

I want to show it in months, then weeks, then days, etc. If they are zero, they should be omitted.我想以月、周、天等为单位显示。如果它们为零,则应将其省略。

You can use moment.duration() for this.您可以为此使用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>

If you want solution in pure JavaScript try this如果你想要纯 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 ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM