user13548628
user13548628

Reputation:

How to handle dynamic date in javascript

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>

Upvotes: 2

Views: 1186

Answers (3)

Mohsen Alyafei
Mohsen Alyafei

Reputation: 5547

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

Upvotes: 0

dauffret
dauffret

Reputation: 1417

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

Upvotes: 1

ichigolas
ichigolas

Reputation: 7725

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

Upvotes: 2

Related Questions