1
var today = new Date(); 
var times = today.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
    if ("2:40 pm" > times) {
     console.log("true")
    } 
    else {
  console.log("false")

    }

It's comparing only the first digit of string (2). so how to compare time along with am and pm

  • 2
    `timestamp` is your best friend (i.e: `d1.getTime() - d2.getTime()` if the output is positive then `d1 > d2` if it's negative then `d2 > d1` ) – kemicofa ghost Dec 19 '19 at 10:24
  • But as per my requirement, I need to check the only time in am/pm format, please help with only time format. please don't include date format here – Naveen kumar Dec 19 '19 at 10:28
  • Does this answer your question? [How do you display JavaScript datetime in 12 hour AM/PM format?](https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format) – Cid Dec 19 '19 at 10:37
  • No, the question is how to compare the current time with another time in am/pm format (ex:3:30 pm compare with 10:30 am ) – Naveen kumar Dec 19 '19 at 10:43
  • @Naveenkumar the duplicate allows you to get the time with your expected format. You can then simply compare – Cid Dec 19 '19 at 12:01

2 Answers2

0

I'd recommend using moment.js

This is how the snippet using moment.js would look like:

var compareTo = "Thu, 03 Mar 2016 21:18:39 +0000";
var then = moment(date);

if (compareTo > then) {
  $('.result').text('Date is past');
} else {
  $('.result').text('Date is future');
}

Parsing dates with AM/PM:

y =( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
x= ( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );

console.log(x>y)
Aqua 4
  • 771
  • 2
  • 9
  • 26
0

Basically I have two variables, one is for the current date and the other for testing time. The test is for comparing hours, given that PM is greater then AM.

var today = new Date(); 
var dummy = new Date();

/**
 * set time to test against
 * setHours(HH, MM, SS)
**/
dummy.setHours(13, 35, 11);

if (today.getHours() > dummy.getHours()) {
 console.log("Dummy First --> Today Later");
} else {
 console.log("Today First --> Dummy Later");
}
DESH
  • 530
  • 2
  • 11
  • 29