Using JavaScript to display dates as numbers

Hey there! I'm diving into the world of JavaScript and have a question that might be beginner level.

So, here's my code snippet:

<script>
    var curdate = new Date();
    document.write(curdate.setFullYear(1989, 07, 26));
</script>

Instead of displaying the date in a normal format, I'm getting a number like: 620154050573. Even when I tried converting it to a string before displaying, it didn't change. Can someone help me understand why this is happening?

Thanks!

Answer №1

When you use the setFullYear function, the returned value is a Number, not a Date.

var current = new Date();
current.setFullYear(1990, 10, 15)
document.write(current);

It's important to note that adding a prefix of 0 before a number in JavaScript signifies that the number should be treated as octal.

Answer №2

To update the full year of a date object, simply use the setFullYear() method and then display the updated date. For example:

myDate.setFullYear(1999, 11, 31);
console.log(myDate);

When using the setFullYear method, it will return a value that represents the number of milliseconds between the updated date object and midnight on January 1, 1970.

Return Value: A Number, which indicates the difference in milliseconds between the specified date object and Jan 1, 1970

You can find more information about the setFullYear method in the official documentation: http://www.w3schools.com/jsref/jsref_setfullyear.asp

Answer №3

JavaScript Date objects in JavaScript are structured around a time value that represents the number of milliseconds since January 1, 1970 UTC.

To format a Date object, you can utilize one of the various Date object methods available. Check out the MDN Data.prototype documentation for more information.

In the example provided below, I used the toUTCString method, but make sure to explore the link above to discover the method that suits your needs best.

<script>
  var currentDate = new Date();
  currentDate.setFullYear(1989, 07, 26)
  document.write(currentDate.toUTCString());
</script>

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

Creating a Thrilling Triple Image Transformation on Hover using Material-UI

Here is a Codepen showcasing a triple hover effect on an image: Codepen I attempted to recreate this effect as a styled component in React Typescript using MUI and MUI Image, but encountered an error with my styling that is preventing it from working in m ...

Hiding a particular form amidst a sea of other forms on a webpage

There are several forms included on the page, with each form having its own submit button. The desired behavior is that when a user clicks the submit button on a form, only that specific form should disappear while the other forms remain visible. It is im ...

Is it possible to utilize various return values generated by a regex?

Working on a project where I am utilizing regex to extract links from a Google Calendar XML feed. The links appear in the following format: <a href="http://www.drsketchysdublin.com/event-registration/?ee=11">http://www.drsketchysdublin.com/event-reg ...

Tips for displaying or concealing elements in React with Hooks

For a closer look at what I'm referring to, visit the CodeSandbox. If you click on the View Profile button of a player, you'll notice that the player's profile loads below the cards. This happens because the Switch/Router statement is posit ...

Make sure to keep Vue-Cookies intact even when closing the browser or tab

I have integrated vue-cookies into my Vue application. The code I'm using to store a cookie is as follows: $cookies.set('authUser', authUserObj); The object authUserObj contains the access_token. However, when I close and reopen the ta ...

Retrieve geographical JSON data from the mapbox API to identify if a point falls within a polygon area

I came across a helpful tutorial that guided me on how to check if a point lies within a specific polygon displayed by a marker: The tutorial worked smoothly by fetching the polygon geoJSON data using ajax and integrating it into the map. However, I alrea ...

The insertion order of newly created documents is not guaranteed in MongoDB

Lately, I've noticed a strange behavior when using mongoose to create new records. Instead of being placed at the end of all existing documents, sometimes the new record ends up in a random position within the collection. I'm really confused and ...

Modify a unique element within an array stored in the state using Redux toolkit

I'm currently attempting to modify a property of an object within an array stored in my state. export const changeStatus = createAsyncThunk('changeStatus', async (arg) => { const todo = arg const response = await axios.put(`${URL} ...

JavaScript - Getting the name of a sub-class when extending the Error class

In my application, I have custom Errors that I wanted to check for later using the constructor name. However, when I extend Error in my classes, the constructor name always displays as "Error" instead of the actual name I assigned to it. I conducted some ...

Warning: Accessing a string index without initialization: 0

Currently, I am encountering some errors while attempting to insert only non-empty rows with multiple inserts. The problem seems to lie within the for loop, but I am struggling to comprehend the error and resolve it. The list of errors includes: Notice ...

The issue of button onclick textfield validation malfunctioning

Within this container, there is a text field identified as 'codeCityId' along with a button that triggers an onclick method. When the button is clicked, the function will verify the input. function click()={ var valid = $('#codeCityId' ...

AngularJS modal behaving oddly when checkboxes are used

My Angular app is available in this plunker. Upon clicking the button, a modal dialog opens displaying a list of items. Two of these items are pre-checked based on conditions set in the checkbox table input. The following function handles pushing and spl ...

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

What is the best way to conceal an ag-grid column when viewing on a mobile

I am attempting to conceal a column in ag-grid when viewing it on mobile devices. For my vue.js application, I have tried using the code snippet below, but unfortunately, it is not functioning as expected. { headerName: "Action", field: "action", minWidt ...

Extremely sluggish pagination in JQGrid following the implementation of a filter through the filter toolbar

I've encountered a problem while using jqGrid with LOAD ONCE and client-side paging. The addition of a filter toolbar has significantly slowed down the paging process after applying any kind of filter. $(gridElement).jqGrid({ postData: post, ...

The div is being duplicated by jeasy-ui

In the main.php file <?php //echo "session check: ".$_SESSION['session_array']; //exit; session_start(); // Start Session if( !isset($_SESSION['session_array']) ) { header("Location: index.p ...

JavaScript came to a screeching halt

I was having issues with my JavaScript that validated a form, but now it's not working. I recently applied my template to the application and at some point, the functionality stopped. Any suggestions on what might have caused this? <!DOCTYPE HTML ...

The react-native-video-controls package was used in React Native. When the onBack event was triggered, it successfully navigated back to the initial screen. However, upon returning

https://i.stack.imgur.com/GsS3d.png https://i.stack.imgur.com/HYBOU.png Attached are screenshots showing the issue I am experiencing with my video player. When I click the back button, the screen does not return to its initial state and the flatlist items ...

Customize Bootstrap 4 Card Width in Card Decks for a Fixed Number of Cards per Row

My website features a deck of cards, and I must say, they are quite responsive. They adhere to the set amount per row for each resolution and maintain consistent height. However, there is one issue that bothers me - when there are 2 cards in a row, with 2 ...

Vue: Conditionally display a division depending on v-if, excluding cases where the div returns null

Within my HTML, I have implemented conditional rendering using v-if <div v-if="showdiv"> <p>Content 1 appears here</p> </div> <div v-if="!showdiv"> <p>Content 2 appears here</p> < ...