Formatting dates and times without a library in JavaScript
A guide on how to use the built-in Date object in JavaScript to manage and manipulate date and time data.
21 November, 2022
1
1
0
Contributors
Dates and times can be tricky in JavaScript. You always want to be sure you are doing it correctly. Luckily, because JavaScript has a built-in Date object, it makes working with dates and times much easier. In fact, there are many different methods on the Date object that can be used to do different things with dates. In this blog, I'll run through a few of these methods.
A quick note on the Date object
The built-in Date object in JavaScript offers us a set of APIs for working with date and time data. A Date object instance represents a single point in time. The instance is in a platform-independent format.
Creating an instance
Current Date / Time
There are multiple ways you can get an instance (or representation) of the current date and time.
Using the constructor
Using the Date() function
This returns a string representation of the current date and time
Using a static method, .now()
This returns a number that represents the milliseconds elasped since 1 January 1970 UTC
Other ways to create an instance
Parsing strings
With the new Date() constructor (or Date.parse() ). Strings must be compliant with the ISO 8601 format, YYYY-MM-DDTHH:mm:ss.sssZ.
The example below is discouraged and may not work in all runtimes/browsers. A library like moment or dayjs can help if other string formats are needed.
Passing integers in the constructor
This syntax is
new Date(year, month, day, hours, minutes, seconds, milliseconds);
This
month
is 0-indexed, meaning 0
is January and 11
is DecemberEpoch (Unix) Timestamp
Epoch timestamp is the number of seconds elapsed since January 1, 1970 (midnight UTC/GMT)
Sytanx
new Date(milliseconds)
Get Epoch in seconds
Date Methods
We can also manage and manipulate dates and times using the methods provided by the Date object.
Accessing Date components
Get the year (4 digits, e.g., 2022)
Get the month. The month is zero-indexed (i.e., 0 - 11).
Get the day of the month, from 1 to 31.
Get the day of the week. This is also zero-index (i.e., from 0 to 6). The first day is always Sunday (This is not so in some countries but can’t be changed).
The methods,
getHours()
, getMinutes()
, getSeconds()
, getMilliseconds()
get the corresponding time components.All the methods above return the components relative to your local time zone. UTC-counterparts are available for each method which return values relative to UTC. Simply insert
UTC
right after get
in the method name.Destructuring assignment example
Setting Date Components
The following methods allow to set date/time components
•
setFullYear(year, [month], [date])
•
setMonth(month, [date])
•
setDate(date)
•
setHours(hour, [min], [sec], [ms])
•
setMinutes(min, [sec], [ms])
•
setSeconds(sec, [ms])
•
setMilliseconds(ms)
•
setTime(milliseconds)
(sets the whole date by milliseconds since 01.01.1970 UTC)Every one of them except setTime() has a UTC-variant
Some methods can set multiple components at once. For example, setHours() gives you the option to set minutes, seconds and milliseconds as well. These options are not modified if not included in the method call.
Formatting
Variations of the toString() method. Returns various string representation of a Date instance.
The Intl.DateTimeFormat object
On modern browsers and runtimes, JavaScript includes an Internationalization API that allows for language-sensitive date and time formatting. You can start using it right away without having to import a massive date formatting library.
Conclusion
In today's blog post, we learned how to format date/time data in JavaScript. There are many libraries that handle this for us already, but if you're working in a legacy codebase or have performance reasons for wanting to avoid a library, you may have to handle date/time formatting natively.
develevate
howto
toolstipstricks