Currently using Mongoose and Luxon to showcase the event date, however, I am encountering an issue where the displayed date is one day earlier than expected

Currently, I am working with Mongoose and Luxon to present a date chosen by the user from a form. However, there seems to be an issue where the date is being console logged as one day, but appearing on the page as the previous day.

Below is my model setup:

const mongoose = require("mongoose");
const { DateTime, Settings } = require("luxon");

// Setting up time zone
console.log(Settings);

const Schema = mongoose.Schema;

let AccomplishmentSchema = new Schema({
  dateInput: {
    type: Date,
    required: true,
  },
  textInput: {
    type: String,
    required: true,
  },
});

AccomplishmentSchema.virtual("dateInput_formatted").get(function () {
  return DateTime.fromJSDate(this.dateInput).toLocaleString(DateTime.DATE_FULL); // format 'YYYY-MM-DD
});

module.exports = mongoose.model("Accomplishment", AccomplishmentSchema);

The following displays the console log alongside what appears on the webpage:

 dateInput: 2023-01-01T00:00:00.000Z,
 textInput: 'etst',

December 31, 2022 etst

It seems like this discrepancy could be related to some sort of time conversion error. Despite adjusting the time zone and settings, the problem persists, leaving me unable to identify a solution.

Answer №1

The functionality of Luxon is operating as expected and the screen is displaying accurate information. The issue lies within the data stored in your MongoDB database.

When parsing a date, many libraries take into account the current time zone. I currently reside in Switzerland.

const moment = require("moment");
console.log( moment('2023-01-01').toDate() )
> 2022-12-31T23:00:00.000Z

const { DateTime } = require("luxon");
console.log( DateTime.fromISO('2023-01-01').toJSDate() )
> 2022-12-31T23:00:00.000Z

const dayjs = require('dayjs')
console.log( dayjs('2023-01-01').toDate() )
> 2022-12-31T23:00:00.000Z

However, the default JavaScript new Date() constructor does not!

console.log( new Date('2023-01-01') )
> 2023-01-01T00:00:00.000Z

This behavior may vary depending on your environment and scripting engine.

It is advisable to utilize Luxon when parsing input data - ensure to use .toJSDate() to convert the DateTime object back to a Javascript native Date object.

Luxon typically utilizes the system time zone by default. You have the option to modify it:

const { DateTime, Settings } = require("luxon");
Settings.defaultZone = 'America/New_York';

If you are unconcerned with the exact time, you can also make use of startOf('day')

Settings.defaultZone = 'America/New_York';
DateTime.now().startOf('day').toJSDate()
> 2023-01-13T05:00:00.000Z

DateTime.now().startOf('day').toISO()
> '2023-01-13T00:00:00.000-05:00'

Answer №2

Understanding JS's Date functionality is crucial, as it does not inherently account for time zones. Instead, it tracks the milliseconds since Jan 1, 1970 in UTC. When accessing Date methods, results are adjusted based on the user's time zone or remain in UTC. The core data stored within Date lacks timezone specifics.

Consider the example of new Date(0), equivalent to new Date('1970-01-01T00:00Z').

For instance, with a computer set to Europe/Paris time zone, executing

new Date(0).toLocaleDateString('en-US')
yields '1/1/1970'. Shifting to
America/Los_Angeles</code alters the output to <code>'12/31/1969'
.

The discrepancy arises from Date representing midnight on Jan 1, 1970 in UTC. Consequently, this moment corresponds to varied local dates across different time zones.

Situations like displaying date-only values encounter challenges due to timezone variations. For example, presenting Date value 2023-01-01T00:00:00.000Z in a California browser triggers a Dec 31, 2022 display instead.

To address such issues, specifying that dates are in UTC alleviates concerns:

utcDateStoredInMongoDB = new Date ('2023-01-01T00:00:00.000Z');
// Obtain year, month, day in UTC.
year = utcDateStoredInMongoDB.getUTCFullYear();
month = utcDateStoredInMongoDB.getUTCMonth();
day = utcDateStoredInMongoDB.getUTCDate();
// Initialize new Date reflecting user's time zone.
dateForDatePicker = new Date(year, month, day);
// Utilize date for picker.
dateForDatePicker.toLocaleDateString();
// => '1/1/2023'

// Conversely, extract year/month/day in current zone and convert to UTC date.
dateReturnedByDatePicker = new Date(2023, 02, 15);
year = dateReturnedByDatePicker.getFullYear();
month = dateReturnedByDatePicker.getMonth();
day = dateReturnedByDatePicker.getDate();
dateToStoreInMongoDB = new Date(Date.UTC(year, month, day));
dateToStoreInMongoDB.toISOString();
// => '2023-03-15T00:00:00.000Z'

Improvements are expected with the introduction of the upcoming JavaScript Temporal API, simplifying handling of date-time complexities through features like Temporal.PlainDate.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ngSwitchCase provider not found

While following a tutorial and trying to implement what I learned, I encountered an error that I'm having trouble understanding. The browser console shows an error message stating [ERROR ->]<span *ngSwitchCase="true">, but I can't figure ...

Recording errors within the NodeJS / Express / React technology stack

Seeking help on logging errors in a React and NodeJS/Express application. How can I track errors occurring on the backend API server, whether in the node console or an external file? For instance, suppose there's an endpoint "/api/example" responsibl ...

Storing input data in a JavaScript array instead of sending it through an AJAX request

I've been grappling with this issue for quite some time now, and I just can't seem to wrap my head around it. While there are a few similar solutions out there, none of them address my exact problem. Here's the scenario: I have a form where ...

Stop the stream coming from getUserMedia

After successfully channeling the stream from getUserMedia to a <video> element on the HTML page, I am able to view the video in that element. However, I have encountered an issue where if I pause the video using the controls on the video element a ...

Ways to insert text at the start and end of JSON data in order to convert it into JSONP format

Currently, I am working on a project where I need to add a prefix "bio(" and a suffix ")" to my JSON data in order to make it callable as JSONP manually. I have around 200 files that require this modification, which is why I am looking for a programmatic ...

The i18n feature in Nuxt 3 retrieves language locales from an external API

While working on my Nuxt 3 app, I encountered an issue when trying to integrate i18n. Despite conducting extensive research, I couldn't find any helpful information, hence I have a question. I am utilizing i18n with Prismic CMS. The locales array is s ...

Angular UI Grid failing to properly display date formatting

Currently, I am using Angular's UI Grid to showcase multiple columns. However, I am facing an issue with formatting the date column. The date is being displayed as /Date(1451346632162-0000)/, and similar formats. I have attempted to apply filters in ...

Running two different wdio.config.js files consecutively

Is it possible to run two wdio.config.js files with different configurations, one after another? Here is how the first configuration file is defined in the code: const { join } = require('path'); require('@babel/register') exports.co ...

Is there a way to automatically scroll vertically to a specific line in HTML?

Trying to explain this is a bit tricky. I am looking to add an element to the HTML that prompts the browser to scroll vertically to its location automatically when loaded, similar to an anchor. So: | visible area | | content html | | content html | ...

Why will the experimental activation of React concurrent features in Nextjs 12 disable API routes?

I just upgraded to Next.js version 12 and set up some API routes (e.g. "/api/products"). These routes were functioning properly, but when I enabled concurrentFeatures: true in my next.config.ts, the API routes stopped working. The console display ...

KeyBy lodash method stores values in an object using the specified property as keys

There are multiple items stored in an array: "objects": [ { "category": "XXXXX", "item_name": "over_pkg_0", "price": 230 }, { "category": "XXXXX", "item_name": "over_pkg_1", "price": 54 }, ...

"Utilize JavaScript to structure JSON, eliminate redundant entries, and calculate the total number

I'm feeling a bit disoriented, as I have this dataset in json format with timestamps and ids arranged like so: [{ "date":"2016-11-18 19:20:42","id_pa":"7" },{ "date":"2016-11-18 19:04:55","id_pa":"5" },{ "date":"2016-11-19 20:53:42","id_pa":"7" ...

The GIF Loader fails to animate while an AJAX request is in progress

Displaying a DIV element containing a loading GIF image while waiting for an AJAX call response. Initially, the DIV element is hidden. Upon clicking a checkbox, the loader DIV is shown, followed by the completion of the AJAX call, and then hiding the load ...

What is the best way to create a universal variable that can be accessed across all routes in an Express/

Exploring the world of nodejs and express, I have turned to the Parse API for my backend database needs. At the moment, I have an ajax post triggered on page load to one of my routers /getuser, which retrieves the current user if they are logged in. I am ...

AgGrid's magical dropdown feature

Struggling to integrate a bootstrap-4 dropdown menu with AgGrid, I'm facing an issue where the data table overlaps the dropdown when the html is present. Attempts to increase the z-index have not yielded results. Below is the html code snippet: < ...

Displaying genuine HTML content in a React application using Algolia Instantsearch

After setting up a demo app using React with an Algolia search feature, I uploaded some indices into Algolia. The content consists of raw HTML. Is there a way to display this content as real HTML using Algolia? ...

When using the `coffee-util` library, an issue may arise if the `require('./module')` function ends

When I develop using CoffeeScript 1.6.3, I simply run my application with coffee myapp. I also use coffee -c . to check the resulting .js files. However, when I try running coffee myapp again, the coffee utility for require(./module) uses .js files inste ...

Is there potentially a memory leak in this code? If there is, what steps can be taken to eliminate it?

Recently I inherited a project from my senior colleagues that focused on seamless page reloading using AJAX. The code is filled with numerous functions like this one: function iCreateProblems() { //some random code document.getElement ...

Squashing the `require()` method in nwJS using emberJS

I am facing an issue with my nwjs application that connects to a web address hosting an ember application. I need to access the node context within the ember application to determine the user's operating system for updating purposes. I attempted to do ...

Tips on automatically navigating to a new webpage after the user logs in with react.js

I'm exploring the world of ReactJS and currently experimenting with how to redirect a user after they register on my page. Below is a snippet from my App.js file where I have set up a registration form. import React, { useState } from "react" ...