Hasunohana
Hasunohana

Reputation: 615

Why date compare javascript function is not working?

I'm trying to valid the CheckIn, CheckOut datete, but when checkIn===checkOut was be false instead of true. How you can see, both are object and both equal.

function inverterData(date) {
  try {
    const regex = '^([0-9]{2})([0-9]{2})([0-9]{4})';
    const dataFormatada = date.match(regex);
    return `${dataFormatada[2]}/${dataFormatada[1]}/${dataFormatada[3]}`;
  } catch (error) {
    return [{ mensagem: 'Date is not valid!' }];
  }
}

function isValidDate(d) {
  return d instanceof Date && !isNaN(d);
}

function validacao(checkin, checkout) {
  // Check if entries is not null, undefined ou empty
  if (!checkin || !checkout) return [{ mensagem: 'Fill CheckIn and / or Checkout.' }];
  // Allow only string types
  if (typeof (checkin) === 'string' && typeof (checkout) === 'string') {
    let checkIn = new Date(inverterData(checkin));
    let checkOut = new Date(inverterData(checkout));
     console.log(typeof(checkIn),typeof(checkOut));
     console.log(checkIn,checkOut);
     console.log(checkIn===checkOut);
    // Date is not valid
    if (!isValidDate(checkIn) || !isValidDate(checkOut)) return [{ mensagem: 'Date is not valid' }];
    // CheckIn cannot be equal Checkout
    if (checkIn === checkOut) return [{ mensagem: 'CheckIn cannot be equal to checkOut' }];

    // Checkout can be less than CheckIn
    if (checkOut < checkIn) return [{ mensagem: 'Checkout can be less than' }];
  } else {
    return [{ messagem: 'Data type is not allowed.' }];
  }
  return [];
}
console.log(validacao('11022021','11022021'));

Anyone help to understand why It is helping?

Upvotes: 0

Views: 69

Answers (2)

Mazen Al Khatib
Mazen Al Khatib

Reputation: 308

Why compare dates as strings instead of using moment.js? it's much easier and would give you more control over such operations.

Also, you can convert the date to timestamp and check if both within the same day.

Upvotes: 1

Vlad
Vlad

Reputation: 477

You cant compare objects in javascript using ===.

If you want to check dates you should convert it to string first, for example.

Please check - this threads for more details JavaScript Date Object Comparison

Object comparison in JavaScript

Upvotes: 1

Related Questions