检查是否在Javascript中通过了AM / PM当前时间

时间:2018-10-01 17:15:32

标签: javascript date time

以下是给定时间:

11:20 AM
or 01:00 PM

我需要使用Javascript(不带库)检查当前时间是否过去

这是我在Java中执行的操作:

    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
    String currentTime = sdf.format(new Date());
    currentTime = timeConverter(currentTime,24);

    Date date = new Date() ;
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm", 
    Locale.ENGLISH) ;
    dateFormat.format(date);

    if(dateFormat.parse(currentTime).after(dateFormat.parse(startTime24)))
                isClassComplete.setImageDrawable(progressIcon);

帮我用Java语言做。

2 个答案:

答案 0 :(得分:0)

var a = new Date('1/10/2018 19:30')
var b = new Date('1/10/2018 20:00')
var difference = Math.floor((b - a) / 1000 / 60);
console.log(difference + ' minutes difference.');

区别是时间以秒为单位。

答案 1 :(得分:0)

如果您只有一个没有日期的时间字符串,则可以将时间转换为一个公分母,例如分钟,然后进行比较。例如

/* Convert time string to minutes
 * @param {string} time: format hh:mm am/pm
 * @returns {number} time converted to minutes
*/
function timeToMins(time) {
  var b = time.split(/[:\s]/);
  return b[0]%12*60 + +b[1] + (/pm\s*$/i.test(time)? 720 : 0);
}

// E.g.
[['10 : 23pm','10:23am'],   // Tolerant of differing whitespace 
 ['12:12 am','12:12   pm'],
 ['12:12 pm','12:12 am   ']
].forEach(times => console.log(
    `${times[0]} < ${times[1]}? ${timeToMins(times[0]) < timeToMins(times[1])}`
  )
);

尽管以上内容可以容忍不同的空格,但是您应该在处理前向字符串添加验证以确认格式,如果不是必需的格式,则返回有意义的消息。您可能还需要扩展它以支持可选的秒和几分之一秒。