获得下次尊重时间格式而不是以往的时间格式 [英] Get the next time that respect a time format and not a pervious one

查看:108
本文介绍了获得下次尊重时间格式而不是以往的时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将时间移至下一个"6:00:00",我正在使用时刻:

let shiftEnd =  moment("06:00:00", "HH:mm:ss")
console.log(shiftEnd.inspect())

它使我得到了之前的6:00:00,即与now()相同的日期.

moment("2017-07-31T06:00:00.000")

now()是:

moment("2017-07-31T12:20:57.076")

获取尚未通过的下一个凌晨6点的最佳方法是什么?

解决方案

您将获得当天的时刻对象,因为作为时刻 )和 add 1天(如果需要).

这里有个例子:

 let shiftEnd =  moment("06:00:00", "HH:mm:ss")

if( shiftEnd.isBefore(moment()) ){
  shiftEnd.add(1, 'd')
}

console.log(shiftEnd.inspect())
console.log(shiftEnd.format()) 

 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> 

I am trying to get the time to the next "6:00:00", I am using moment:

let shiftEnd =  moment("06:00:00", "HH:mm:ss")
console.log(shiftEnd.inspect())

It gets me the previous 6:00:00, the one with the same day as now().

moment("2017-07-31T06:00:00.000")

now() is:

moment("2017-07-31T12:20:57.076")

What's the best way to get the next 6am that's not passed yet?

解决方案

You are getting a moment object for the current day because, as moment Default section states:

You can create a moment object specifying only some of the units, and the rest will be defaulted to the current day, month or year, or 0 for hours, minutes, seconds and milliseconds.

You can simply test if your moment object is in the past (using isBefore) and add 1 day if needed.

Here a live example:

let shiftEnd =  moment("06:00:00", "HH:mm:ss")

if( shiftEnd.isBefore(moment()) ){
  shiftEnd.add(1, 'd')
}

console.log(shiftEnd.inspect())
console.log(shiftEnd.format())

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

这篇关于获得下次尊重时间格式而不是以往的时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆