2

I am stuck about 2 problems in JavaScript but I don't find the solution.

My first problem: we are on 25-05-2020, if the user enters the date of yersteday or a previous date. I would like to display an error message.

I have to use the now() method ? I tried this ??

const date = new Date(date_start)

    if(date.getFullYear() < Date.now()) {
        document.getElementById('date_startError').innerHTML = " ** the date is obsolete ! ";
        return false;
 
}

My second problem: How to handle also the futur date? For example, I want to limit the date futur to one maximum year?

Example: we are on 2020-05-25 if the user enters on the input on 2020-05-27 I would like to display an error message.

Edit

function validation()
{
    
    var date_start = document.getElementById('date_start').value;


    const date = new Date(date_start);
    const oneYearFromNow = now.setFullYear(now.getFullYear() + 1);

    if(date < oneYearFromNow) {
        document.getElementById('date_startError').innerHTML = " ** the date is obsolete ! ";
        return false;
 
    } 
    
}
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>
<body>
<form action="#" onsubmit="return validation()" >
<br>
<label>Date start : </label>
<br>
<input type="date" name="date_start" id="date_start">
<br>
<span id="date_startError"></span>
<br>
<input type="submit" value="ok">
</form>
</body>
</html>
Nimantha
  • 6,405
  • 6
  • 28
  • 69
  • 2
    use moment.js for date comparison, it is much easier that way – msapkal May 25 '20 at 21:09
  • Does this answer your question? [Compare two dates with JavaScript](https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – Marco May 25 '20 at 21:15
  • Moment.js is good. I personally prefer using cherry-picked functions from date-fns. In any case, unless I needed a complex feature like date localization, I wouldn't install a new dependency. – ichigolas May 25 '20 at 21:19

3 Answers3

2

Date.now returns the EPOCH: the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC. Looks like you are comparing it (an integer) with a date, and that may be the problem.

If you already have a date instance handy, you can instead use new Date(), which returns current datetime and use the built-in comparison operators for dates:

date > new Date()

You can also get a date's EPOCH using .getTime(), and then you compare it to Date.now():

date.getTime() > Date.now()

For the one year validation you could do something like this:

const now = new Date()
const oneYearFromNow = now.setFullYear(now.getFullYear() + 1);
date < oneYearFromNow
ichigolas
  • 7,595
  • 27
  • 50
  • Thank you for your help. I am trying your code for `the one year validation`, I have tried but it doesn't work. I edited my first message. I don't understand where is the problem? –  May 25 '20 at 21:33
  • 1
    You reversed the condition `date < oneYearFromNow` checks that date is between now and one year from now, i.e: that is valid. In your particular case you want the opposite, i.e: `if (date > oneYearFromNow) { showError() }` – ichigolas May 25 '20 at 21:40
  • 1
    1 Jan 1970 is the ECMAScript [epoch](https://www.dictionary.com/browse/epoch), [*Date.now*](https://tc39.es/ecma262/#sec-date.now) returns a [time value](https://tc39.es/ecma262/#sec-time-values-and-time-range) that is milliseconds since the epoch. – RobG May 25 '20 at 23:59
1

In order to compare dates, it's easier to use a library like moment.js or date-fns.

An example with date-fns could be:

https://codesandbox.io/embed/modest-moon-b8mub?fontsize=14&hidenavigation=1&theme=dark

 const dateEntered = new Date("2019-05-26")
  const now = new Date();

  if (isBefore(dateEntered, now)) {
    return (
      <h1>Date cannot be in the past</h1>
    )
  }
  if (intervalToDuration({
    start: new Date("2019-05-26"),
    end: now
  }).years < 1) {
    return (

      <h1>Date cannot be over one year in the future</h1>
    )
  }

docs for isBefore: https://date-fns.org/v2.14.0/docs/isBefore

docs for intervalToDuration: https://date-fns.org/v2.14.0/docs/intervalToDuration

dauffret
  • 1,387
  • 1
  • 15
  • 22
0

Here is a function to calculate the date difference in days. If the output is - number it is in the past, if a positive number it is in the future.

// Calculate the difference in days

function dateDiffDays(date1, date2) {
  return Math.round((new Date(new Date(date2)).setHours(12)-new Date(new Date(date1)).setHours(12))/8.64e7);
}

// ============ test ==============
var today=Date.now()                 // today's date
console.log(dateDiffDays(today,"2020-05-25"))    // yesterday -1
console.log(dateDiffDays(today,"2020-05-27"))    // tomorrow 1
console.log(dateDiffDays(today,"2021-05-27"))    // 366 days in future
console.log(dateDiffDays(today,"2019-05-27"))    // -365 days in te past
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Mohsen Alyafei
  • 4,765
  • 3
  • 30
  • 42