How do I get the current date in JavaScript?
To access the current date in JavaScript, profound usage of new Date()
instance is required:
Here, a Date
object corresponding to now is created, and it's output in an ISO format. Further refining the display can be achieved through methods like .toISOString()
, .toLocaleDateString()
, and .toTimeString()
.
Date Formatting
Standard date format
The date in standard form (specifically YYYY-MM-DD
) could be quickly achieved using the toISOString()
and slice()
methods (slicing the pizza of time anyone? 🍕):
Locale-specific date formatting
Need your date hand-tailored? Use .toLocaleDateString()
:
Need to further polish the format based on a locale? Customize the date with options like a pro tailor:
UTC and ISO-based Dates
To get an accurate snapshot of UTC timing, .toISOString()
is your friend:
Time Adjustments and Cross-Browser Compatibility
Setting the time to midnight
Regardless of time zone, if you want your date to start at midnight (because who doesn't enjoy midnight snacks?), you can set the time to midnight:
Ensuring cross-browser compatibility
To ensure cross-browser compatibility (Google, Firefox, Safari- oh my!), adjust the format:
Advanced Formatting with Libraries
For advanced formatting as unique as your coffee order, consider using an external library like Date.format.min.js
or dateFormat.min.js
:
These libraries offer compound formats, constants, and more sophisticated pretty date formats (because who doesn't like pretty things?). They even allow for escaping characters in the format string, offering full customization (because sometimes escape is necessary):
Working with Day and Month Names
Translating numbers to names
To translate month and day numbers to names, make arrays your accomplice. After all, "March" sounds better than "3":
Master Punctuation
Are your dates losing their "st", "nd", "rd", "th" suffixes? Time for a rescue mission with domEnder
:
Was this article helpful?