oneberenjena
oneberenjena

Reputation: 165

Setting ISO date time to zero

I'm trying to compare a Date comming from a Mongo query that has a date in ISO format. The date is the following:

2018-01-20T00:00:00.000Z

I want to compare today's date with this, so my approach was to create a new date and set its time to zero like this:

var today = new Date();
today.setHours(0,0,0,0); //Sat Jan 20 2018 00:00:00 GMT-0800 (PST)

With this, it seems like the time is set to zero. The problem comes when I convert it to ISO string for comparison:

console.log(today.toISOString()); //2018-01-20T08:00:00.000Z

As you can see, it sets everything to zero but hour, that remains at 08. I can't get to set this hour to zero.

Upvotes: 7

Views: 8823

Answers (2)

Mohit Saud
Mohit Saud

Reputation: 115

The above comment is the correct answer. My task was to find all the bookings in the present date, past date, and future date. I had to query the MongoDB database. The above ISO String method helped me to solve my problem. Thank You very much.

 const { past, present, future } = req.query;

  let today = new Date();
  today.setUTCHours(0, 0, 0, 0);
  today.toISOString();

  let bookings;

  if (past === 'past') {
    bookings = await Booking.find({
      booking_user: req.user.userId,
      booking_checkin: { $lt: today },
    }).sort('-booking_status : cancelled');
  } else if (present === 'present') {
    bookings = await Booking.find({
      booking_user: req.user.userId,
      booking_checkin: { $eq: today },
    }).sort('-booking_status : cancelled');
  } else if (future === 'future') {
    bookings = await Booking.find({
      booking_user: req.user.userId,
      booking_checkin: { $gt: today },
    }).sort('-booking_status : cancelled');
  } else {
    bookings = await Booking.find({
      booking_user: req.user.userId,
    }).sort('-booking_status : cancelled');
  }

  res.status(StatusCodes.OK).json({ count: bookings.length, bookings });

Upvotes: 0

var today = new Date();
today.setUTCHours(0,0,0,0);

document.getElementById('val').innerHTML = today.toISOString();
<label>Date: (ISO String)</label>
<div id="val">
<div>

today.setUTCHours(0,0,0,0);

This will set the UTC hours giving you the desired output.

Upvotes: 14

Related Questions