乐闻世界logo
搜索文章和话题

How to compare two dates with javascript

4个答案

1
2
3
4

In JavaScript, there are multiple ways to compare two dates. Here are several common methods:

1. Using Date objects directly

The JavaScript Date object can be used to represent dates and times. Directly comparing two Date objects using comparison operators (<, >, <=, >=) is a straightforward approach:

javascript
let date1 = new Date('2023-04-01'); let date2 = new Date('2023-04-02'); if (date1 < date2) { console.log('date1 is earlier than date2'); } else if (date1 > date2) { console.log('date1 is later than date2'); } else { console.log('date1 is the same as date2'); }

2. Using getTime() method

The getTime() method of the Date object returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This can be used for precise comparison of two dates:

javascript
let date1 = new Date('2023-04-01'); let date2 = new Date('2023-04-02'); if (date1.getTime() < date2.getTime()) { console.log('date1 is earlier than date2'); } else if (date1.getTime() > date2.getTime()) { console.log('date1 is later than date2'); } else { console.log('date1 is the same as date2'); }

3. Comparing specific parts of the date

If you want to compare specific parts of a date (e.g., only the year), you can use methods provided by the Date object, such as getFullYear(), getMonth(), getDate(), etc., to retrieve the values and then compare them:

javascript
let date1 = new Date('2023-04-01'); let date2 = new Date('2023-04-02'); if (date1.getFullYear() < date2.getFullYear()) { console.log('date1 is in an earlier year than date2'); } else if (date1.getMonth() < date2.getMonth()) { // Note: Months are zero-based, where 0 represents January. console.log('date1 is in an earlier month than date2'); } else if (date1.getDate() < date2.getDate()) { console.log('date1 is on an earlier day than date2'); } else { console.log('The specific parts compared are equal'); }

Example

Suppose you are building a website where users input their birthday, and you need to check if the input date is in the past. You can implement this as follows:

javascript
function isPastDate(inputDate) { let today = new Date(); let birthDate = new Date(inputDate); // Zero out the time components of today today.setHours(0, 0, 0, 0); return birthDate < today; } // Assume user input is '2000-05-20' let userInput = '2000-05-20'; if (isPastDate(userInput)) { console.log('The entered date is in the past.'); } else { console.log('The entered date is not in the past.'); }

In this example, the isPastDate function checks if the user's input date is earlier than the current date. If so, the function returns true, indicating it is a past date. Before comparison, we set the time components of today to zero to ensure only the date part is compared.

2024年6月29日 12:07 回复

Relational operators <, <=, >, and >= can be used to compare JavaScript dates:

javascript
var d1 = new Date(2013, 0, 1); var d2 = new Date(2013, 0, 2); d1 < d2; // true d1 <= d2; // true d1 > d2; // false d1 >= d2; // false

However, equality operators ==, !=, ===, and !== cannot be used to compare date values because as explained in the MDN documentation:

  • In both strict and abstract comparisons, two different objects are never equal.
  • An expression comparing objects is true only if the operands reference the same object.

You can use any of the following methods to compare date values for equality:

javascript
var d1 = new Date(2013, 0, 1); var d2 = new Date(2013, 0, 1); /* * Note: d1 == d2 returns false as described above */ d1.getTime() == d2.getTime(); // true d1.valueOf() == d2.valueOf(); // true Number(d1) == Number(d2); // true +d1 == +d2; // true

Both Date.getTime() and Date.valueOf() return the number of milliseconds since January 1, 1970, 00:00 UTC. The Number function and unary operator + implicitly call the valueOf() method.

2024年6月29日 12:07 回复

In JavaScript, the simplest way to compare dates is to first convert them to Date objects and then compare these date objects.

Below, you'll find an object with three functions:

  • date.compare(a,b) Returns a number:
    • -1 if a < b
    • 0 if a = b
    • 1 if a > b
    • NaN if a or b is an invalid date
  • date.inRange(d, start, end) Returns a boolean or NaN:
    • true if d is between start and end (inclusive)
    • false if d is before start or after end
    • NaN if one or more dates is invalid
  • date.convert Used by other functions to convert inputs to Date objects. Inputs can be:
    • Date object: returned as-is.
    • Array: interpreted as [year, month, day]. Note: month is 0-11.
    • Number: interpreted as milliseconds since January 1, 1970 (a timestamp)
    • String: supports various formats, such as "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009", etc.
    • Object: interpreted as an object with year, month, and date properties. Note: month is 0-11.

// Source: http://stackoverflow.com/questions/497790

javascript
var dates = { convert:function(d) { // Converts the date in d to a date-object. The input can be: // a date object: returned without modification // an array : Interpreted as [year,month,day]. NOTE: month is 0-11. // a number : Interpreted as number of milliseconds // since 1 Jan 1970 (a timestamp) // a string : Any format supported by the javascript engine, like // "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc. // an object : Interpreted as an object with year, month and date // attributes. **NOTE** month is 0-11. return ( d.constructor === Date ? d : d.constructor === Array ? new Date(d[0],d[1],d[2]) : d.constructor === Number ? new Date(d) : d.constructor === String ? new Date(d) : typeof d === "object" ? new Date(d.year,d.month,d.date) : NaN ); }, compare:function(a,b) { // Compare two dates (could be of any type supported by the convert // function above) and returns: // -1 : if a < b // 0 : if a = b // 1 : if a > b // NaN : if a or b is an illegal date // NOTE: The code inside isFinite does an assignment (=). return ( isFinite(a=this.convert(a).valueOf()) && isFinite(b=this.convert(b).valueOf()) ? (a>b)-(a<b) : NaN ); }, inRange:function(d,start,end) { // Checks if date in d is between dates in start and end. // Returns a boolean or NaN: // true : if d is between start and end (inclusive) // false : if d is before start or after end // NaN : if one or more of the dates is illegal. // NOTE: The code inside isFinite does an assignment (=). return ( isFinite(d=this.convert(d).valueOf()) && isFinite(start=this.convert(start).valueOf()) && isFinite(end=this.convert(end).valueOf()) ? start <= d && d <= end : NaN ); } }
2024年6月29日 12:07 回复

The Date object can be used to achieve what you need—create a Date object for each date, then use comparison operators like >, <, <=, and >=.

Equality operators ==, !=, ===, and !== require you to use date.getTime() as shown below:

javascript
var d1 = new Date(); var d2 = new Date(d1); var same = d1.getTime() === d2.getTime(); var notSame = d1.getTime() !== d2.getTime();

It's important to note that directly comparing Date objects for equality is not feasible:

javascript
var d1 = new Date(); var d2 = new Date(d1); console.log(d1 == d2); // prints false (incorrect!) console.log(d1 === d2); // prints false (incorrect!) console.log(d1 != d2); // prints true (incorrect!) console.log(d1 !== d2); // prints true (incorrect!) console.log(d1.getTime() === d2.getTime()); // prints true (correct)

For those curious, the documentation for date.getTime() states:

Returns the numeric value of a specified date, as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for dates before this time.)

I recommend using a dropdown menu or similar restricted date input instead of a text field to avoid falling into the input validation nightmare.

2024年6月29日 12:07 回复

你的答案