Exploring the JavaScript Date Object

Julia
3 min readAug 19, 2020

--

The Date object is a built-in object in JavaScript that stores the date and time.

A new Date() instance without arguments provided creates an object corresponding to the current date and time. JavaScript will use the browser’s time zone and display a date in a following format.:

new Date()

=> Sun Aug 16 2020 13:32:59 GMT-0400 (Eastern Daylight Time)

returns a Date object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters.

Date object with given parameters JS produce an object using following pattern :
new Date(year, month, day, hours, minutes, seconds)
You have to provide at least 2 arguments (year and month)
Example:

On the example above JS used 2 parameters you provided, but set hour/minutes/second to 00:00:00 and day to 01 as they were not provided. Please pay attention that JS counting month from 0 to 11, so 5th month is June. Also the year argument must have 4 digits, if you provide year in two digits format , it will be interpreted as 19xx:

Another way to create a date Object is passing a string as an argument. This way has less restrictions, so any of the following will return the same date instance.

new Date (“Mar 27 2019”)
new Date(“27 Mar 2019”)
new Date (“2019–3–27”)
new Date (“2019/3/27”)
new Date (“2019 march 27”)

=> Fri Mar 27 2019 00:00:00 GMT-0400 (Eastern Daylight Time)

The output format of new Date() is long and consist of many components. Imagine that you need to render DOB of users in a mm-dd-yyyy format. We need a way to extract only 3 components (year, month, date) from the Date object. JS provides numbers of built-in methods for formatting and managing Date object. Calling following methods on new Date() object we can get access to certain date components we need and leave out the rest :

.getFullYear()
.getMonth() (from 0 to 11)
.getDate() (day of month from 1 to 31)
.getDay() (day of the week)

Now we can create DOB in any different format we want.

Using array of month we can have month in a literal format:

JS also provide lots of methods for extracting a time. These methods also should be called on a new Date() instance. There are examples of the most useful ones.

.getHours(),
.getMinutes(),
.getSeconds(),

.toTimeString(),
.getSeconds(),
.toLocalTimeString()

The last method return time in 24 h format!

--

--

Julia
Julia

No responses yet