简体   繁体   English

javascript获取时间范围

[英]javascript get time range

I have an ajax request that returns a date and time. 我有一个返回日期和时间的ajax请求。 my ajax output is 7/22/2017, 3:35:51 PM , How can I get the time and have a condition between 9:00am to 5:00pm. 我的ajax输出是7 7/22/2017, 3:35:51 PM ,我如何获取时间并在9:00 am到5:00 pm之间有一个条件。 Thank you in advance. 先感谢您。

$.ajax({
          async: false,
          type: "POST",
          url: apicall,
          success: function (response) {
           console.log(response);
               var offsets = response.dstOffset * 1000 + response.rawOffset * 1000 // get DST and time zone offsets in milliseconds
            var localdate = new Date(timestamp * 1000 + offsets) // Date object containing current time of Tokyo (timestamp + dstOffset + rawOffset
              console.log(localdate.toLocaleString()) // Display current Tokyo date and time

          }

    }); 

Using momentjs would be easier, in my opinion 我认为使用momentjs会更容易

getting the current time is as simple as moment() 获取当前时间就像moment()一样简单

to check if it's between a time range: [ http://momentjs.com/docs/#/query/is-between/] 检查它是否在时间范围之间:[ http://momentjs.com/docs/#/query/is-between/]

This works for me. 这对我有用。

You can create 3 new dates, with your string date, one to check, second to be the upper date to check and the third to be the lower date to check. 您可以创建3个新日期,其中一个字符串日期,一个要检查,第二个是要检查的较高日期,第三个是要检查的较低日期。 The second and the third you need to update to 9:00 AM and 5:00 AM respectively. 您需要将第二个和第三个分别更新为9:00 AM和5:00 AM。 Then you can check your input date. 然后,您可以检查您的输入日期。

 // yes: var s = '7/22/2017, 5:35:51 AM'; var d = new Date(s); var upperD = new Date(s); var lowerD = new Date(s); upperD.setHours(9); upperD.setMinutes(0); upperD.setSeconds(0); lowerD.setHours(5); lowerD.setMinutes(0); lowerD.setSeconds(0); console.log(upperD >= d && d >= lowerD ? 'yes' :'no'); // no: var s = '7/22/2017, 4:35:51 AM'; var d = new Date(s); var upperD = new Date(s); var lowerD = new Date(s); upperD.setHours(9); upperD.setMinutes(0); upperD.setSeconds(0); lowerD.setHours(5); lowerD.setMinutes(0); lowerD.setSeconds(0); console.log(upperD >= d && d >= lowerD ? 'yes' :'no'); 

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

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