JavaScript: Dates
JavaScript has a built-in Date object that allows you to use it in various ways.
To use the Date object, you assign a variable as a new Date, like this:
The Date
object accepts six parameters: year, month, day, minutes, seconds, and milliseconds. You don't need to use all the parameters.
If you don't insert any values in the parentheses ()
, the parameters default to the current date and time.
Example Use of the Date Object
To set a date to 12/12/12, you might write:
Now you can apply various methods to eclipse
to manipulate the Date object. For example, let's suppose you want to know what day of the week this is. You would write:
The result is 6. This means that 12-12-2012 falls on a Friday. (Remember that the first day of the week is a 0, not a 1.)
Here's another example:
This returns 3, which corresponds to Wednesday.
Available Methods for the Date Object
The Date object has a variety of methods:
The getTime Method
The .getTime
method seems odd (returning milliseconds since 1970) but is actually useful in conditional statements. You can't ask if two dates are equal to each other, because dates aren't regular numbers. However, you can ask which date has a larger number of milliseconds since 1970.
Essentially, the getTime
method is a way of converting dates to numbers.
Here's how you might use getTime
:
Using the setDate Method
In addition to .getDate
, there are equivalent methods for setting the date using setDate
. The following are available methods for setDate
:
About Tom Johnson
I'm an API technical writer based in the Seattle area. On this blog, I write about topics related to technical writing and communication — such as software documentation, API documentation, AI, information architecture, content strategy, writing processes, plain language, tech comm careers, and more. Check out my API documentation course if you're looking for more info about documenting APIs. Or see my posts on AI and AI course section for more on the latest in AI and tech comm.
If you're a technical writer and want to keep on top of the latest trends in the tech comm, be sure to subscribe to email updates below. You can also learn more about me or contact me. Finally, note that the opinions I express on my blog are my own points of view, not that of my employer.