Какое сравнение двух дат правильное js
Перейти к содержимому

Какое сравнение двух дат правильное js

Сравнение двух дат в JavaScript

В этом руководстве мы рассмотрим, как сравнивать даты в ванильном JavaScript, используя встроенные методы и операторы, с примерами.

  • Автор записи

Вступление

Даты – очень распространенный тип данных, с которым работают разработчики. От временных меток определенных действий до отчетов, функций регистрации и ограниченного доступа в системах, требующих подписки, – нам часто приходится сравнивать даты.

То есть, мы сравниваем, после или до какой-либо даты, является ли дата сегодняшней, сколько дней между датами и т.д.

В этой статье мы рассмотрим, как сравнить две даты в JavaScript, что поможет нам определить, находится ли дата до или после другой.

Объект даты в JavaScript

Веб-разработчики обычно используют внешние пакеты (например, Moment.js) для обработки операций с датой. Но по мере развития современного Интернета в JavaScript появился новый конструктор объектов под названием Date для обработки операций с датой и временем.

Это означает, что вам не нужна внешняя библиотека для выполнения элементарных проверок и операций, что упрощает их выполнение в Vanilla JS.

Класс Date очень прост для понимания – он просто хранит время Unix, измеряемое в миллисекундах.

Время Unix измеряется как количество секунд, прошедших с эпохи Unix (00:00:00 UTC 1 января 1970 года), которая является совершенно произвольной датой.
Даже если эта реализация кажется немного упрощенной, добавление класса Date было довольно большим улучшением, поскольку наконец-то появился уровень абстракции между разработчиками и необработанными датами.

Теперь давайте рассмотрим различные способы сравнения двух дат с помощью объектов Date.

Сравнение двух дат в JavaScript

Мы можем использовать операторы сравнения < и > для сравнения двух объектов Date, при этом под капотом происходит эффективное сравнение их счетчиков времени. Вы эффективно сравниваете два целочисленных счетчика:

Как мы видим, сравнение дат сводится к преобразованию предоставленных строк в объекты Date и их сравнению с помощью соответствующего оператора сравнения.

Примечание: Операторы равенства (== и ===) не работают с объектами Date, поэтому мы не проверяем, одинаковы ли они.

Другой способ сравнения двух дат – использование встроенного метода getTime().

Метод getTime() возвращает количество миллисекунд, прошедших с момента эпохи Unix. Кроме того, для дальнейшего уточнения и сравнения информации можно использовать методы getDate(), getHours(), getDay(), getMonth() и getYear(), а также другие аналогичные методы.

Кроме того, можно также использовать методы getUTCDay(), getUTCDate(), getUTCHour(), getUTCMinute() и т.д., которые возвращают заданные временные идентификаторы, привязанные к UTC.

Примечание: При таком подходе вы можете использовать операторы равенства!

Давайте рассмотрим пример:

Хотя, поскольку мы работаем с блоками if и if-else, некоторые утверждения никогда не выполняются. Например, 9/10/1997 и 9/10/2000 имеют одну и ту же дату, 9/10, но не один и тот же год.

Например, этот код:

Поскольку мы сравниваем только дату, без учета года.

Заключение

В этой статье мы кратко рассмотрели, как JavaScript работает с датами, используя объекты Date. Затем мы рассмотрели, как сравнивать даты в JavaScript, не забывая о некоторых полезных методах.

Compare two dates with JavaScript

Can someone suggest a way to compare the values of two dates greater than, less than, and not in the past using JavaScript? The values will be coming from text boxes.

user avatar

42 Answers 42

The Date object will do what you want — construct one for each date, then compare them using the > , < , <= or >= .

The == , != , === , and !== operators require you to use date.getTime() as in

to be clear just checking for equality directly with the date objects won’t work

I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.

Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)

user avatar

The easiest way to compare dates in javascript is to first convert it to a Date object and then compare these date-objects.

Below you find an object with three functions:

dates.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 illegal date

dates.inRange (d,start,end)

Returns a boolean or NaN:

  • true if d is between the start and end (inclusive)
  • false if d is before start or after end.
  • NaN if one or more of the dates are illegal.

dates.convert

Used by the other functions to convert their input to a date object. The input can be

  • a date-object : The input is returned as is.
  • 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 : Several different formats is supported, 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.

user avatar

Compare < and > just as usual, but anything involving == or === should use a + prefix. Like so:

The relational operators < <= > >= can be used to compare JavaScript dates:

However, the equality operators == != === !== cannot be used to compare (the value of) dates because:

  • Two distinct objects are never equal for either strict or abstract comparisons.
  • An expression comparing Objects is only true if the operands reference the same Object.

You can compare the value of dates for equality using any of these methods:

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

user avatar

By far the easiest method is to subtract one date from the other and compare the result.

user avatar

Comparing dates in JavaScript is quite easy. JavaScript has built-in comparison system for dates which makes it so easy to do the comparison.

Just follow these steps for comparing 2 dates value, for example you have 2 inputs which each has a Date value in String and you to compare them.

1. you have 2 string values you get from an input and you’d like to compare them, they are as below:

2. They need to be Date Object to be compared as date values, so simply convert them to date, using new Date() , I just re-assign them for simplicity of explanation, but you can do it anyway you like:

3. Now simply compare them, using the > < >= <=

compare dates in javascript

user avatar

Compare day only (ignoring time component):

I no longer recommend modifying the prototype of built-in objects. Try this instead:

N.B. the year/month/day will be returned for your timezone; I recommend using a timezone-aware library if you want to check if two dates are on the same day in a different timezone.

If you construct a Javascript Date object, you can just subtract them to get a milliseconds difference (edit: or just compare them) :

Note — Compare Only Date Part:

When we compare two date in javascript. It takes hours, minutes and seconds also into consideration.. So If we only need to compare date only, this is the approach:

Now: if date1.valueOf()> date2.valueOf() will work like a charm.

The simple way is,

user avatar

SHORT ANSWER

Here is a function that return if the from dateTime > to dateTime Demo in action

Explanation

since you are now having both datetime in number type you can compare them with any Comparison operations

Then

if you are familiar with C# Custom Date and Time Format String this library should do the exact same thing and help you format your date and time dtmFRM whether you are passing in date time string or unix format

Usage

all you have to do is passing any of these format pacified in the library js file

user avatar

you use this code,

user avatar

Via Moment.js

The method returns 1 if dateTimeA is greater than dateTimeB

The method returns 0 if dateTimeA equals dateTimeB

The method returns -1 if dateTimeA is less than dateTimeB

user avatar

BEWARE THE TIMEZONE

A javascript date has no notion of timezone. It’s a moment in time (ticks since the epoch) with handy functions for translating to and from strings in the «local» timezone. If you want to work with dates using date objects, as everyone here is doing, you want your dates to represent UTC midnight at the start of the date in question. This is a common and necessary convention that lets you work with dates regardless of the season or timezone of their creation. So you need to be very vigilant to manage the notion of timezone, particularly when you create your midnight UTC Date object.

Most of the time, you will want your date to reflect the timezone of the user. Click if today is your birthday. Users in NZ and US click at the same time and get different dates. In that case, do this.

Sometimes, international comparability trumps local accuracy. In that case, do this.

Now you can directly compare your date objects as the other answers suggest.

Having taken care to manage timezone when you create, you also need to be sure to keep timezone out when you convert back to a string representation. So you can safely use.

Как сравнить две даты js

Аватар пользователя Ivan Gagarinov

Чтобы сравнить даты, можно их преобразовать в объекты Date и сравнить обычным способом. Однако если даты одинаковые, то они не будут равны, так как сравнение идёт по ссылкам. Чтобы добиться корректного сравнения дат, можно использовать метод getTime() :

  • О проекте
  • Карьера в Хекслете
  • Хекслет Колледж
  • Отзывы студентов
  • Истории успеха
  • Магазин мерча

Hexlet Ltd. Itälahdenkatu 22 A, 00210 Helsinki, Finland VAT ID: FI26641607

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *