Строковое сравнение дат на JavaScript
Пусть у нас есть две даты в следующем текстовом формате:
В таком случае можно выполнить сравнение этих дат и узнать, какая из этих дат больше:
Каким образом происходит сравнение этих дат? Дело в том, что наши даты представляют собой строки и JavaScript сравнивает их как строки. То есть он сначала сравнивает первые символы двух дат: если они одинаковы, то JavaScript сравнивает вторые символы, и так далее, пока не найдет отличия. Благодаря тому, что в нашем формате даты сначала расположен год, потом месяц, а потом день, и возможно такое сравнение.
Дело в том, что если цифра первого года оказывается больше цифры второго года, значит уже не имеет значения, что там с месяцами и днями — первый год точно больше. Если же годы совпадают, то больше будет та дата, у которой больше месяц. А если и месяцы совпадают, то больше будет та дата, у которой больше день. Ну, а если и дни одинаковы, то и даты равны.
Важно также, чтобы даты были в одном формате. В нашем случае разделителями частей дат являются дефисы. Это, конечно же, не обязательно. Например, можно поставить точки:
Или вообще убрать разделители:
Главное, чтобы сравнение было корректным, размещение должно быть следующим: сначала год, потом месяц, потом день.
Напишите код, который сравнит две приведенные ниже даты и выведет сообщение о том, какая из них больше:
Дата без года
Необязательно сравнивать года. Дата может состоять просто из месяца и дня:
Напишите код, который сравнит две приведенные ниже даты и выведет сообщение о том, какая из них больше:
Попадание даты в промежуток
Пусть есть три промежутка: с 1 января по 8 марта, с 9 марта по 17 июня, с 18 июня по 31 декабря. Пусть у нас также есть какая-то дата, содержащая месяц и день. Давайте определим, в какой промежуток попадает эта дата:
Дана дата, содержащая месяц и день. Определите знак Зодиака, на которую приходится эта дата.
JavaScript Date Comparison – How to Compare Dates in JS
Joel Olawanle
A date is one of the most common datatypes developers use when creating real-world applications.
But often, devs struggle with this datatype and end up using date libraries like Moment.js for simple tasks that aren’t worth the large package size that comes with installing an entire package.
In this article, we will learn how to perform date comparisons in JavaScript. If you need the code quickly, here it is:
This will return:
When we think of date comparison in JavaScript, we think of using the Date object ( Date() ) and, of course, it works.
The date object allows us to perform comparisons using the > , < , = , or >= comparison operators, but not the equality comparison operators like == , != , === , and !== (unless we attach date methods to the date Object).
Let’s begin by learning how to perform comparisons using only the date object, and then we’ll see how to perform equality comparisons using the date object alongside date methods.
How to Perform Date Comparison With the Date Object in JavaScript
Suppose we want to compare two dates in JavaScript. We can easily use the Date Object ( Date() ) this way:
The above will return that both dates are the same because we didn’t pass different dates:
Let’s now pass in different date values:
This will now return the following:
Fortunately, the above handles equality as the last option when the first two conditions fail. But suppose we try to handle equality as the condition this way:
It will return the following, which is wrong:
How to Perform Equality Comparison With JavaScript
To handle equality comparison, we use the date object alongside the getTime() date method which returns the number of milliseconds. But if we want to compare specific information like day, month, and so on, we can use other date methods like the getDate() , getHours() , getDay() , getMonth() and getYear() .
This will return:
We can pass in different dates into the date object so as to compare:
As expected this will return:
Note: With the getTime() method we can perform all forms of date comparison using all comparison operators, which are > , < , <= , >= , == , != , === , and !== .
How to Perform Specific Date Comparisons
Suppose we want to compare specific date values like the year. Then we can use the .getYear() date method this way:
Conclusion
In this article, you have learned how to do date comparisons in JavaScript using the date Object without having to install any library.
Сравните две даты в JavaScript
В этом посте мы обсудим, как сравнить две строки даты в JavaScript. Решение должно определить, является ли первая строка даты больше, меньше или равна второй строке даты.
Предположим, что заданные строковые значения представляют допустимую дату, указанную в формате, соответствующем версии ИСО 8601 календарная дата.
1. Использование объекта даты
Здесь идея состоит в том, чтобы преобразовать заданные строки в Date объекты с помощью Date() конструктор. Затем сравните оба Date объекты, использующие операторы отношения > , < , <= или же >= . Следующий пример демонстрирует.
Compare Two Dates in JavaScript
Dates are a really common data type developers work with. From timestamps of certain actions, to reports, sign up features and limited-time access in systems that require subscriptions — we oftentimes have to compare dates.
That is, we compare if a date is after or before another, if the date is today, how many days there are between dates, etc.
In this article, we'll take a look at how to compare two dates in JavaScript, helping us deduce whether a date is before or after another.
The Date Object in JavaScript
Web developers commonly use external packages (like Moment.js) to handle date-time operations. But, as the modern web evolved, JavaScript introduced a new object constructor called Date to handle date-time operations.
This means that you don't need an external library to perform rudimentary checks and operations, which makes it easier to perform these things in Vanilla JS.
The Date class is really simple to understand under the hood — it just stores Unix time measured in milliseconds.
Unix time is measured as the number of seconds elapsed since the Unix epoch (00:00:00 UTC 1 January 1970), which is a completely arbitrary date.
Even though this implementation seems a bit simplistic, the addition of the Date class was quite a big improvement, since there was finally a level of abstraction between developers and raw dates.
Now, let's look at different ways to compare two dates using Date objects.
Comparing Two Dates in JavaScript
We can use comparison operators like < and > to compare two Date objects, and under the hood, their time counters are effectively compared. You're effectively comparing two integer counters:
This results in:
As we can see, comparing dates just boils down to converting the provided strings into Date objects and comparing them with an appropriate comparison operator.
Note: Equality operators ( == and === ) don't work with Date objects, so we don't explicitly check if they're the same.
Another way to compare two dates is by using the built-in getTime() method.
The getTime() method returns the number of milliseconds elapsed since the Unix epoch. Additionally, you can use the, getDate() , getHours() , getDay() , getMonth() and getYear() methods to further specify and compare information, amongst other similarly named methods.
Additionally, you can also use the getUTCDay() , getUTCDate() , getUTCHour() , getUTCMinute() , etc. methods, which return the given temporal identifiers, zoned specifically to UTC.
Note that with this approach, you can use equality operators!
Let's take a look at an example:
This results in:
Though, since we're working with if and if-else blocks, some statements never get to execute. For example, 9/10/1997 and 9/10/2000 have the same date, the 9/10 , though, not the same year.
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
For example, this code:
Would result in:
Since we're just comparing the date, without the year in mind.
Conclusion
In this article, we've briefly gone over how JavaScript handles dates using Date objects. Then, we've covered how to compare dates in JavaScript, keeping some useful methods in mind.