Date Object
The JavaScript Date object is a great tool for using dates and times in your web application. Check out the practical example used for generating timestamps for an example chat app.
The JavaScript Date
object is a way to utilize dates and times within your web application.
According to Mozilla Developer Network:
Date
objects are based on a time value that is the number of milliseconds since1 January 1970 UTC
.
Why? What does that even mean though? Well at one point a group of humans decided to establish that January 1, 1970
will be declared as Unix Epoch Time. Therefore, anything referring to the Date
object is relative to this date. Y'know...I guess you've gotta start somewhere, right?
Let's take a closer look at the syntax, examples of using the specified syntax, and a practical example. 🕰 Time to get started!
Syntax
new Date();
new Date(value);
new Date(dateString);
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
Using The Syntax Examples 🕐
new Date();
Using the Date
object without passing any arguments will give you the date and time that the object was instantiated.
var exampleDate = new Date();
console.log(exampleDate); // Returns the current time at the moment of instantiation
new Date(value);
Passing an integer value
to the Date
object, representing the number of milliseconds since Unix Epoch Time(January 1st, 1970). For instance, if you were to pass 0
as the value
then it would return Thu Jan 1 1970 00:00:00 GMT-0000
. One important thing to note is that your browser will typically return the value in Greenwich Mean Time (GMT) in your given timezone, though this part can be adjusted if need be.
var exampleDate = new Date(670849458699);
console.log(exampleDate);
// Returns Fri Apr 05 1991 06:04:18 GMT-0500 (Eastern Standard Time)
new Date(dateString);
Passing in a dateString
to the Date
object will return the full GMT formatted date string. The dateString
passed in must be able to parsed by the Date.parse()
method. With that said, any "traditional" date format should do the trick.
var anotherExampleDate = new Date('12/23/1993')
console.log(anotherExampleDate); // Returns Thu Dec 23 1993 00:00:00 GMT-0500 (Eastern Standard Time)
var anotherExampleDate = new Date('December 23, 1993')
console.log(anotherExampleDate); // Returns Thu Dec 23 1993 00:00:00 GMT-0500 (Eastern Standard Time)
var anotherExampleDate = new Date('Dec 23 1993')
console.log(anotherExampleDate); // Returns Thu Dec 23 1993 00:00:00 GMT-0500 (Eastern Standard Time)
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
You can also choose to pass in just the year
and the monthIndex
. Note that the monthIndex
is zero-based so January
would be a monthIndex
of 0
.
var millenniumBug = new Date(2000, 0);
// Never forget the 'Millennium bug'
console.log(millenniumBug);
// Returns Sat Jan 01 2000 00:00:00 GMT-0500 (Eastern Standard Time)
Optionally you can pass in the day
, hours
, minutes
, seconds
, and milliseconds
to the Date
object which will return you the precise date you have specified.
var preciseDate = new Date(2017, 1, 5, 10, 24, 12);
console.log(preciseDate);
// Returns Sun Feb 05 2017 10:24:12 GMT-0500 (Eastern Standard Time)
Practical Example: Chat App Timestamps 💬 ⏱
Using the Date()
is hands-down a very powerful tool when dates and times are needed for your web application. But how exactly can we leverage the power of the almight Date()
object?
Let's try it out
In this example, we assume that we have a chat application 🗣 and we need to create the ability to display a message along with a timestamp as to when the message was sent.
const timeStamp = () => {
const date = new Date(); // Instantiate new date
let h = date.getHours(); // Get the hours in 24hr format
const dayOrNight = h > 12 ? 'pm' : 'am';
// If h is greater than 12, set dayOrNight to 'pm'
// Otherwise set to 'am'
h = h > 12 ? h % 12 : h;
// If h, in 24hr format, is greater than 12
// Get remainder of h divided by 12 in order to
// Get the correct hours in 12hr format
let m = date.getMinutes(); // Get the minutes
m = m > 10 ? m : '0' + m
// If m is greater than 10, do nothing
// Otherwise if m is less than 10,
// Append a '0' to the front of m
const msgSentAt = `${h}:${m}${dayOrNight}`; // Format date information into a nice looking timestamp
return msgSentAt; // Return the time message was sent at from the function so we utilize it in our sendMessage function
}
function sendMessage(user, msg) {
console.log(`${user}: ${msg}`); // Display the users name and their message
console.log(timeStamp()); // Display the timestamp
}
// Lastly let's call the send message function
sendMessage("Tim", "Hey what's going on! What time are you headed over to the Y-Combinator event?");
// Returns
// Tim: Hey what's going on! What time are you headed over to the Y-Combinator event?
// 8:31pm // or whatever time for the message was received for that matter
Note: There are countless other ways to utilize the Javascript Date
object. Check out MDN for the complete list!
Wrapping Up 📝
The Javascript Date
object is an essential tool to have in your developer toolkit 🛠. Definitely play around with it some more to fully understand the true power of it. This example only just scratched the surface!
Stay Tuned 📺
If you have any questions or improvements, or if you'd like to see additional examples, feel free to reach out to me anytime at [email protected]
. If you're enjoying my posts, please subscribe below! 👇
Help us improve our content