Creation of Date object

Trying to create a new Date object with the constructor new Date(24, 2, 1, 0, 0 ,0) is causing an issue where it defaults to using setYear instead of setFullYear, resulting in the year being set as 1924. While this may work in most cases, I need the ability to set any given year.

Attempts to use a Date string format like Feb 2, 24 00:00:00 still resulted in the year 2024. Referencing the Date MDN documentation did not provide a successful workaround.

As a workaround, I opted for the following solution:

var d1 = new Date();
    d1.setFullYear(y);
    d1.setMonth(m);
    d1.setDate(d);
    d1.setHours(0);
    d1.setMinutes(0);
    d1.setSeconds(0);

However, this method is quite cumbersome and not ideal. I am curious if there is a better solution to this issue?

Answer №1

According to the guidelines outlined in the Ecma Script specification, the year value in the Date constructor is processed in the following manner:

If the year value is not a NaN and falls within the range of 0 to 99 when converted to an integer, then the year is set as 1900 plus the converted integer value; otherwise, the year remains as it is.

Answer №2

After testing in both Chrome and Firefox, it appears that the Date constructor behaves differently depending on the values passed:

new Date(24,2,12,0,0,0) //Wed Mar 12 1924 00:00:00 GMT+0100 (Romance Standard Time)
new Date(2024,2,12,0,0,0) //Tue Mar 12 2024 00:00:00 GMT+0100 (Romance Standard Time)

It seems that the constructor uses setYear or setFullYear based on the value provided.

Answer №3

Consider the following solution:

let date = new Date(year, month, day, 0, 0, 0);
date.setFullYear(year);

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

Guide to correctly setting up the b-table component in vue-test-utils

Currently, I am utilizing the buefy css library in conjunction with the vue.js framework. The challenge I am facing involves unit testing my vue component (Foo), which includes the b-table component from buefy: <b-table :data="foo" class=&quo ...

How can I tally the number of channels within a specific category using discord.js?

I'm in the process of creating a bot that can provide me with the number of channels within a specific category. if (strMessage === "!outline") { var outlineSize; message.reply("There are " + outlineSize + " outlines curr ...

Leveraging Trustpilot TrustBoxes within a Next.js environment

I'm currently implementing a Trustpilot TrustBox into a Next.js application. Inside my componentDidMount, I have the following code: var trustbox = document.getElementById('trustbox'); window.Trustpilot.loadFromElement(trustbox); In the ...

Ajax Complete adds Jquery two times in a row

I have a simple ajax complete call that is designed to add some text after an ajax load finishes. However, I'm encountering an issue where the information is sometimes displayed multiple times. I suspect there might be something missing in my approach ...

Display a partial form in Rails using Ajax

There is a form displayed in the image below: Next, I aim to render this partial from an ajax call, specifically from .js.erb. However, I am unsure how to pass an object to f from the partial. Take a look at the image below for reference: Is there a way ...

When I avoid using a string ref, I encounter the error message "Error: Function components are not allowed to have string refs"

Recently, I created a new component const Projects = () => { const state ={ activeItemID: 1 } const CarouselRef = useRef(null); const NextSlide = () => { CarouselRef.current.style = "opacity: 0"; } return( <Co ...

tips for closing mat select when clicked outside

When a user clicks on the cell, it should display the value. If the user clicks outside the cell, the input field will close and show the field value. I am facing an issue on how to implement this with mat select and mat date picker. Any suggestions? Than ...

Passing a reference to a react functional component (react.FC) results in a type error: The property ref is not recognized on the type 'IntrinsicAttributes & Props & { children: ReactNode}'

Currently, I am working on mastering the utilization of forward refs. In a functional component (FC), I am trying to initialize all my refs and then pass them down to its child components so that I can access the canvas instances of some chartjs charts. Ho ...

It appears that the Facebook share feature is not picking up any meta OG tags

There seems to be an issue with my Facebook share functionality as it's not reading any of the meta tags. It is indicating that the required properties such as og:url, og:type, og:title, og:image, og:description, and fb:app_id are missing. <script ...

Navigate between tabs with a single click

Hey there! I'm having trouble putting together a webpage that features a sidebar. I want to make it so that clicking on one of the links at the top will switch the tab and its content accordingly. However, the current code I have isn't working an ...

Tips for adjusting image and div sizes dynamically according to the window size

In my quest, the end goal is to craft a simplistic gallery that closely resembles this particular example: EXAMPLE: This sample gallery is created using Flash technology, but I aim to develop mine utilizing HTML, CSS & Javascript to ensure compatibil ...

Display or conceal a div element depending on the user's choice

I am looking to hide inactive divs, but whenever I reload the page, all tab contents merge into one. The screenshot below shows the issue I'm facing. Screenshot Below is the code snippet: $('.tab a').on('click', function ...

I am encountering an issue while attempting to set up admob for my react native application, as I am facing

Encountering an error The file "/BuildProductsPath/Release-iphoneos/XCFrameworkIntermediates/GoogleAppMeasurement/WithoutAdIdSupport/GoogleAppMeasurement.framework/GoogleAppMeasurement(APMAdExposureReporter.o)" does not have bitcode. Suggestions include r ...

Nested ng-repeat in AngularJS by numeric value

Looking to create a sliding carousel layout for displaying a bunch of data with 8 points per slide. The desired structure is as follows: Slide datapoint 1 datapoint 2 datapoint 3 datapoint 4 datapoint 5 datapoint 6 datapoint 7 ...

Calculate the length of a JSON array by using the value of one of its

What is the most efficient way to obtain the length of a JSON array in jQuery, based on the value of its attribute? As an illustration, consider the following array: var arr = [{ "name":"amit", "online":true },{ "name":"rohit", "online":f ...

Differences between JavaScript closures and traditional functions

Recently, I came across an example of JavaScript closure that left me puzzled. The example code is as follows: function makeSizer(size) { return function() { document.body.style.fontSize = size + 'px'; }; } var size12 = makeSizer(12); ...

Error Encountered: Nested textarea not supported in HTML

Below is the code I am working with. The issue lies with the <textarea>. In my form, there is a textarea. When I insert another <textarea> within the ckeditor value (HTML), the inner textarea ends up closing the parent textarea. Is there a sol ...

Vue.js encountering an issue of receiving null for the JSON data upon the initial loading phase

Currently, I am expanding my knowledge on vue.js and experimenting with calling a json file to parse the data. Although everything seems to be functioning as intended, whenever I refresh the page, there is a momentary blank screen before the data loads. In ...

The functionality of the anchor tag is restricted in both Chrome and Safari browsers

I'm having an issue with HTML anchor tags not working properly in Chrome and Safari. Instead of scrolling up, the page scrolls down when clicked. Here is the HTML code I'm using: <a id="to-top"></a> <a class="button toTop" href="# ...

Using Jquery to Insert Numbers Inside Brackets to Selection

I am struggling to calculate the sum of numbers in jQuery for selection fields. Currently, my code looks like this. $(function() { $("select").change(function() { updateTotal(); }); updateTotal(); }); function updateTotal() { ...