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

acquire the document via ng-change

I need help converting this code to be compatible with angular.js so that I can retrieve the data URL and send it using $http.post <input type="file" id="imgfiles" name="imgfiles" accept="image/jpeg" onchange="readURL(this);"> function readURL(i ...

Creating a custom script for a search field that retrieves information from an XML document

Attempting to create a script that iterates through an XML file, the provided code currently displays alerts but fails to show information when a valid value is entered into the search field. However, upon removing the error checks and keeping the final ...

`Is there a way to modify the zAxis of a Paper component in Material-UI?`

Hello, I am curious about how to change the z-axis of a paper from MUI. https://i.sstatic.net/iKXLG.jpg The issue I'm facing is that the carousel is overlapping my menu and I need the menu to be on top of everything. Here is how I have it structure ...

I'm struggling to understand why the jQuery find() method isn't functioning as expected

UPDATE: In a twist of events not caused by syntax errors, but rather by a loading issue with the html template, it turns out that the checkbox update was happening prematurely. So if you're searching for an element that seems to be missing, it may sim ...

Modify the CSS when CKEditor is in focus

Implementing CKEditor in a symfony project using the FOS\CKEditor-bundle 1.2. I want to style the entire element containing CKEditor with a border when it is focused, similar to how questions are written or answered on Stackoverflow. By referencing a ...

Is there a problem with AngularJS $state.go() not emitting $stateChangeSuccess?

In my scenario, I have controllers A and B located in different states. When I trigger $state.go('state_b');, Angular switches to state state_b and loads controller B. However, what surprises me is that I do not receive $stateChangeSuccess in my ...

What criteria should I consider when selecting a make for the createTheme components?

After reviewing the documentation for the createTheme component, I noticed examples with MuiButtonBase, MuiButton, and MuiSlider. However, when it comes to adding a button, it's simply called Button, not MuiButton. So, does this mean I just need to p ...

Angular 1.5 component causing Typescript compiler error due to missing semi-colon

I am encountering a semi-colon error in TypeScript while compiling the following Angular component. Everything looks correct to me, but the error only appears when I insert the this.$routeConfig array: export class AppComponent implements ng.IComponentOp ...

What is the best way to extract all "conditions" nested under the key "logic" at the 0th index in a JSON object?

I need to manipulate a nested object by removing every "condition" where the key is "logic" and the value is 0 from it. Here is an example of the object structure: Original input: [ { "conditions": [ { "logic": "AND", "paramet ...

Aligning validation schema with file type for synchronization

Below is the code snippet in question: type FormValues = { files: File[]; notify: string[]; }; const validationSchema = yup.object({ files: yup .array<File[]>() .of( yup .mixed<File>() .required() .t ...

Dealing with Cross-Origin Resource Sharing (CORS) issues when

After completing an Ionic 5 course, I attempted to deploy the backend code written in JS on Github and Heroku. However, when setting up authentication within my application, I encountered the following error: error The backend is built using Node.js and ...

What is the process for uploading a text file into JavaScript?

I'm currently facing an issue with importing a text file from my local computer into JavaScript in order to populate HTML dropdowns based on the content of the file. Despite spending considerable time searching for solutions on stack overflow, I haven ...

Generating div elements of varying colors using a combination of Jinja templating and JavaScript loop

Utilizing jinja and javascript in my template, I am creating multiple rows of 100 boxes where the color of each box depends on the data associated with that row. For instance, if a row in my dataset looks like this: year men women 1988 60 40 The co ...

Exploring the Realm of Javacript Template Literal Capabilities

Is it possible to define a variable inside a template literal and then utilize it within the same template? If this isn't feasible, it appears to be a significant feature that is lacking. const sample = tag` some random words, ${let myvar = 55} addit ...

I developed a Node.js Express server that establishes a connection to a MongoDB database hosted on mLab. I am now looking to integrate CRUD operations with this server from my React application. Can anyone

I built one nodejs app that uses express routing to connect to a mongodb on mlab that listens on a local port. I built a React app with nodejs that is listening on another port. How can I have the React app read and write documents to the database? Any tu ...

Triggering an error message when a user attempts to submit an incomplete angular form

Working on an Angular form where users advance to the next step by clicking a button, but it remains disabled until all fields are valid. I'm wondering how I can implement a custom class to highlight incomplete fields when the user tries to move to t ...

Choosing multiple values in the selectize plugin from the controller: A step-by-step guide

Need help with selecting multiple options I'm utilizing the following plugin: https://github.com/selectize/selectize.js/blob/master/docs/usage.md I have an object as displayed in the image below: https://i.stack.imgur.com/sQsKe.png This is my Client ...

Find and replace string words containing special characters such as $ or !

Looking to process an input string in a specific way - // Input string - 'My pen cost is !!penCost!! manufactured in $$penYear$$ with colors !!penColor1!! and $$penColor1$$' // Processed string 'My pen cost is <penCost> manufactured ...

Tips for simulating the $timeout service with sinon?

I am looking to write a unit test for a method within an Angular controller that uses the $timeout service. However, I have been advised not to use inject in this scenario. Therefore, I need to mock $timeout on my own. Can someone guide me on how I can a ...

Make sure the page preloader is visible before any other content is loaded

Currently, I am working on a straightforward preloader page that remains visible until the main content of the page is completely loaded. Despite the functionality of the loading page, my main concern lies in the quick display of the main content before th ...