开发者

JS Comparing Current and Given Time

I want to compare the current time and a given time inp开发者_JAVA百科utted by the user using JavaScript.


In JavaScript, the current date (including time, to the millisecond) is accessible like this:

var current = new Date();

That gets you a Date object, with many different methods and properties you can use. Among others, you'll be interested in getHours and getMinutes, if what you have from your user is a time.


Javascript has a powerful Date parser built right in. Try something like the following:

function compareDates(dateString)
{
  // Convert the user's text to a Date object
  var userDate = new Date(dateString);

  // Get the current time
  var currentDate = new Date();

  if(isNaN(userDate.valueOf()))
  {
    // User entered invalid date
    alert("Invalid date");
    return;
  }

  var difference = currentDate - userDate;
  alert("The date entered differs from today's date by " + difference + " milliseconds");
}

Edit: If you want to parse time instead of dates, you have to use regular expressions. If the format the user enters is like 10:50pm, you could use something like the following code:

var dateRegex = /(\d\d?):(\d\d)(am|pm)?/;
function parseTime(timeString)
{
  var match = dateRegex.exec(timeString);
  if(!match) return null;
  return {
    hours: match[1]-0, // Subtracting zero converts to a number
    minutes: match[2]-0,
    isPM: match[3].toLowerCase === "pm"
  };
}
console.log(parseTime("10:50pm"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜