得到天,小时和分钟差异时刻js

时间:2018-03-20 13:09:10

标签: javascript momentjs

我有两个日期时间选择器(从,到)。我需要在几分钟(1505分钟)以及白天和时间(2天1小时35分钟)内区分FROM和TO日期。

我使用moment.js

var now = moment('2018-03-28 14:02');
var end = moment('2018-06-02 00:00'); // another date
var duration = moment.duration(end.diff(now));
var days = duration.asDays();
console.log(days) //65.41527777777777

此处的输出为65.4152777777777765天数正确,但如何将41527777777777转换为小时和分钟。 如果我做这个0,41527777777777 * 24 = 9,96666666648我 得到9个小时,再次0,96666666648 * 60 = 57,这是正确的差异

65 day, 9 hour and 57 min

但是,有没有办法直接用moment.js做到这一点?

谢谢

3 个答案:

答案 0 :(得分:4)

没有插件:

var now = moment('2018-03-28 14:02');
var end = moment('2018-06-02 00:00'); // another date
var duration = moment.duration(end.diff(now));

//Get Days and subtract from duration
var days = duration.asDays();
duration.subtract(moment.duration(days,'days'));

//Get hours and subtract from duration
var hours = duration.hours();
duration.subtract(moment.duration(hours,'hours'));

//Get Minutes and subtract from duration
var minutes = duration.minutes();
duration.subtract(moment.duration(minutes,'minutes'));

//Get seconds
var seconds = duration.seconds();
console.log("Days: ",days);
console.log("Hours: ",hours);
console.log("Minutes: ",minutes);
console.log("Seconds: ",seconds);

答案 1 :(得分:3)

不是直接在moment.js内,不,但是this open issue将我引导到this moment.js plugin,这允许格式化持续时间。看起来使用该插件,您可以使用它来获得所需的输出:

duration.format("D [day], H [hour and] m [min]")

答案 2 :(得分:1)

moment.asDays(date)返回float时,您需要使用Math.floor()

function durationAsString(start, end) {
  const duration = moment.duration(moment(end).diff(moment(start)));

  //Get Days
  const days = Math.floor(duration.asDays()); // .asDays returns float but we are interested in full days only
  const daysFormatted = days ? `${days}d ` : ''; // if no full days then do not display it at all

  //Get Hours
  const hours = duration.hours();
  const hoursFormatted = `${hours}h `;

  //Get Minutes
  const minutes = duration.minutes();
  const minutesFormatted = `${minutes}m`;

  return [daysFormatted, hoursFormatted, minutesFormatted].join('');
}

console.log(durationAsString('2018-03-28 14:02', '2018-06-02 00:00'))

console.log(durationAsString('2018-06-01 14:02', '2018-06-02 00:00'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>