Skip to content

Instantly share code, notes, and snippets.

@jim-clark
Created January 29, 2025 11:37
Show Gist options
  • Save jim-clark/f6aedf5dec3e2dad322eddc5e3812eb7 to your computer and use it in GitHub Desktop.
Save jim-clark/f6aedf5dec3e2dad322eddc5e3812eb7 to your computer and use it in GitHub Desktop.

🎩 DATE OFF BY ONE DAY (EARLIER) FIX

If a Mongoose schema has a type of Date and you are using a <input type="date"> to allow the user to enter/select a date, the actual date stored in the database will be one day earlier than specified.

This is because of the way JavaScript's Date() class/constructor, which Mongoose uses to convert a string value into a data object, incorrectly sets the date if the string is in the YYYY-MM-DD format. You can demo this by typing new Date('2025-01-29') in the console - the returned date will be yesterday. Interestingly, new Date('01/29/2025') or even new Date('1-29-2025') do not suffer from this bug.

The most straightforward fix is to append T00:00 (designate the time) to the end of the date string. Try it in the console: new Date('2025-01-29T00:00'). You can code the fix in either the front or the backend (controller), for example:

async function create(req, res) {
  try {  
    req.body.user = req.user._id;
    // Date fix
    req.body.expiration += 'T00:00';
    const post = await Post.create(req.body);
    res.json(post);
  } catch (err) {
    res.status(400).json({ message: 'Post create failed' })
  }
}

Note that using a date/time works as expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment