If you're working with dates and time in your JavaScript code, you're likely familiar with the challenges involved. From handling timezones to formatting dates, it can be a tricky task that requires a deep understanding of the language and its built-in tools.
That's why in this article, we'll dive into some of the advanced techniques and best practices for handling dates and time with JavaScript.
We'll explore topics such as working with time zones, parsing and formatting dates, how to do countdowns and checking for elapsed time since the last action.
This article is designed to be a complete and thorough guide to date & time functions. The alternative way of handling this topic would have been to create ten different blog posts, which I feel is overkill, so feel free to bookmark this page as a reference!
Get the current year
To get the current year, you can use the built-in Date
object.
Here's the code to get the current year:
const currentYear = new Date().getFullYear();
The getFullYear()
method returns the current year as a four-digit number. You can assign the result to a variable to use it elsewhere in your code.
If you need to get the current year as a string, you can simply use the toString()
method:
const currentYearString = new Date().getFullYear().toString();
That's all there is to it!
Get the current date
To get the current date, you can also use the built-in Date
object.
Here's the code to get the current date:
const currentDate = new Date();
The Date
object returns a new instance representing the current date and time. You can assign the result to a variable to use it elsewhere in your code.
If you want to get the current date as a formatted string, you can use various methods of the Date
object to extract the day, month, and year, and then format them as a string.
Here's an example:
const currentDate = new Date();
const day = currentDate.getDate();
const month = currentDate.getMonth() + 1; // add 1 because getMonth() returns a zero-based index
const year = currentDate.getFullYear();
const formattedDate = `${month}/${day}/${year}`;
console.log(formattedDate); // e.g. "2/22/2023"
In this example, we use the getDate()
method to get the day of the month, the getMonth()
method to get the month (remembering to add 1 to the result), and the getFullYear()
method to get the year. We then format these values as a string using template literals.
Get the current time
If you want to get the current time as a formatted string, you can use various methods of the Date
object to extract the hours, minutes, and seconds, and then format them as a string.
Here's an example:
const currentTime = new Date();
const hours = currentTime.getHours();
const minutes = currentTime.getMinutes();
const seconds = currentTime.getSeconds();
const formattedTime = `${hours}:${minutes}:${seconds}`;
console.log(formattedTime); // e.g. "13:45:22"
If you want to display the time in a specific time zone, you can use the toLocaleTimeString()
method, which allows you to specify the time zone as an option:
const currentTime = new Date();
const options = { timeZone: 'America/Los_Angeles' }; // specify the time zone as an option
const formattedTime = currentTime.toLocaleTimeString('en-US', options);
console.log(formattedTime); // e.g. "1:45:22 PM"
In this example, we use the toLocaleTimeString()
method to format the time as a string.
We pass 'en-US'
as the first argument to specify the locale, and we pass an options object as the second argument to specify the time zone.
Get the day of the week
Here's the code to get the day of the week as a number, where Sunday is 0 and Saturday is 6:
const currentDate = new Date();
const dayOfWeek = currentDate.getDay();
The getDay()
method returns the day of the week as a number, where Sunday is 0 and Saturday is 6. You can assign the result to a variable to use it elsewhere in your code.
If you want to get the day of the week as a string, you can create an array of weekday names and use the day of the week as an index to access the corresponding name.
Here's an example:
const currentDate = new Date();
const weekdayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const dayOfWeekString = weekdayNames[currentDate.getDay()];
console.log(dayOfWeekString); // e.g. "Wednesday"
In this example, we create an array of weekday names and use the getDay()
method to get the day of the week as a number. We then use the day of the week as an index to access the corresponding weekday name from the array.
Get timestamp value from a date string
To get the timestamp value from a date string, you can use the built-in Date
object to parse the string and then call the getTime()
method to get the timestamp.
Here's an example:
const dateString = '2023-02-22T13:45:22';
const timestamp = new Date(dateString).getTime();
console.log(timestamp); // e.g. 1645550722000
In this example, we create a date string in ISO format (YYYY-MM-DDTHH:mm:ss) and assign it to the dateString
variable. We then create a new Date
object using the string, which automatically parses it to create a new date object. Finally, we call the getTime()
method on the date object to get the timestamp value in milliseconds since January 1, 1970.
If you have a date string in a different format, you can use various methods of the Date
object to parse it into a Date
object. For example, if your date string is in the format "MM/DD/YYYY HH:mm:ss", you can use the split()
method to extract the components and then use the Date
constructor to create a new date object:
const dateString = '02/22/2023 13:45:22';
const [month, day, year, hours, minutes, seconds] = dateString.split(/[/ :]/);
const timestamp = new Date(year, month - 1, day, hours, minutes, seconds).getTime();
console.log(timestamp); // e.g. 1645550722000
In this example, we use the split()
method to extract the month, day, year, hours, minutes, and seconds from the date string. We then pass these values to the Date
constructor to create a new date object. Note that we subtract 1 from the month value because the Date
constructor expects a zero-based index for the month.
Set different dates and times for a Date instance
To set different dates and times for a Date
instance, you can use various methods of the Date
object to modify the different components of the date and time.
Set the year, month, and day:
const date = new Date();
date.setFullYear(2024);
date.setMonth(4); // note that the month is zero-based, so 4 represents May
date.setDate(13);
Set the hours, minutes, and seconds:
const date = new Date();
date.setHours(15);
date.setMinutes(30);
date.setSeconds(0);
Set the date and time at once using the setTime()
method:
const date = new Date();
date.setTime(1745667000000); // set the timestamp value for January 24, 2025, at 8:10:00 AM
You can combine these methods to set any combination of dates and times that you need.
Here's an example that sets the date to May 13, 2024, at 3:30 PM:
const date = new Date();
date.setFullYear(2024);
date.setMonth(4); // note that the month is zero-based, so 4 represents May
date.setDate(13);
date.setHours(15);
date.setMinutes(30);
date.setSeconds(0);
In this example, we use the setFullYear()
, setMonth()
, and setDate()
methods to set the year, month, and day, respectively. We then use the setHours()
, setMinutes()
, and setSeconds()
methods to set the hours, minutes, and seconds, respectively.
Add or subtract date & time values
To add or subtract date and time values, you can use the built-in Date
object along with the various methods it provides for manipulating dates and times.
Add or subtract days:
const date = new Date();
date.setDate(date.getDate() + 7); // add 7 days
date.setDate(date.getDate() - 3); // subtract 3 days
Add or subtract hours:
const date = new Date();
date.setHours(date.getHours() + 2); // add 2 hours
date.setHours(date.getHours() - 1); // subtract 1 hour
Add or subtract minutes:
const date = new Date();
date.setMinutes(date.getMinutes() + 30); // add 30 minutes
date.setMinutes(date.getMinutes() - 15); // subtract 15 minutes
Add or subtract seconds:
const date = new Date();
date.setSeconds(date.getSeconds() + 45); // add 45 seconds
date.setSeconds(date.getSeconds() - 10); // subtract 10 seconds
Add or subtract milliseconds:
const date = new Date();
date.setTime(date.getTime() + 60000); // add 1 minute (in milliseconds)
date.setTime(date.getTime() - 30000); // subtract 30 seconds (in milliseconds)
In these examples, we use various methods of the Date
object to add or subtract different units of time. Note that when adding or subtracting dates, it's important to use the correct method for the particular unit of time, such as setDate()
for days, setHours()
for hours, and so on.
You can combine these methods to add or subtract any combination of dates and times that you need. Here's an example that subtracts 3 days and 2 hours from the current date and time:
const date = new Date();
date.setDate(date.getDate() - 3);
date.setHours(date.getHours() - 2);
In this example, we use the setDate()
method to subtract 3 days from the current date, and we use the setHours()
method to subtract 2 hours from the current time.
Calculate differences between date & time periods
To calculate the differences between date and time periods, you can use the built-in Date
object along with the various methods it provides for working with dates and times.
Calculate the difference between two dates in milliseconds:
const date1 = new Date('2023-02-22T13:45:22');
const date2 = new Date('2023-02-23T08:30:10');
const diff = date2.getTime() - date1.getTime(); // difference in milliseconds
Calculate the difference between two dates in days:
const date1 = new Date('2023-02-22T13:45:22');
const date2 = new Date('2023-02-26T08:30:10');
const diff = Math.round((date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24)); // difference in days
Calculate the difference between two times in minutes:
const time1 = new Date();
const time2 = new Date();
time1.setHours(9, 30, 0); // set the time to 9:30 AM
time2.setHours(10, 45, 0); // set the time to 10:45 AM
const diff = Math.round((time2.getTime() - time1.getTime()) / (1000 * 60)); // difference in minutes
In these examples, we use various methods of the Date
object to calculate the differences between date and time periods. Note that when calculating differences between dates, it's important to use the getTime()
method to get the timestamp value in milliseconds, and then divide by the appropriate unit of time to get the difference in the desired unit.
You can combine these methods to calculate the difference between any combination of dates and times that you need. Here's an example that calculates the difference between two dates in weeks:
const date1 = new Date('2023-02-22T13:45:22');
const date2 = new Date('2023-03-22T08:30:10');
const diff = Math.round((date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24 * 7)); // difference in weeks
In this example, we use the getTime()
method to get the difference in milliseconds, and then divide by the number of milliseconds in a week to get the difference in weeks.
Check how much time has elapsed
To check how much time has elapsed between two points, you can use the built-in Date
object along with the various methods it provides for working with dates and times.
Calculate the elapsed time in milliseconds:
const start = new Date();
// some long-running operation
const end = new Date();
const elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
Calculate the elapsed time in seconds:
const start = new Date();
// some long-running operation
const end = new Date();
const elapsed = Math.round((end.getTime() - start.getTime()) / 1000); // elapsed time in seconds
Calculate the elapsed time in minutes:
const start = new Date();
// some long-running operation
const end = new Date();
const elapsed = Math.round((end.getTime() - start.getTime()) / (1000 * 60)); // elapsed time in minutes
In these examples, we use the Date
object to get the start and end times, and then calculate the elapsed time by subtracting the start time from the end time. Note that when calculating elapsed time, it's important to use the getTime()
method to get the timestamp value in milliseconds, and then divide by the appropriate unit of time to get the elapsed time in the desired unit.
You can use these methods to check the elapsed time of any operation, whether it's a long-running process or a short calculation. Here's an example that checks the elapsed time of a short operation in milliseconds:
const start = new Date();
// some short operation
const end = new Date();
const elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
if (elapsed > 100) {
console.log(`Operation took longer than expected: ${elapsed} ms`);
} else {
console.log(`Operation completed in ${elapsed} ms`);
}
In this example, we check the elapsed time of a short operation and log a message if the elapsed time exceeds a certain threshold (in this case, 100 milliseconds).
How to do countdown processing
To do countdown processing using JavaScript, you can use the built-in setTimeout()
method to run a function after a certain amount of time has elapsed.
Here's an example:
function countdown(seconds) {
const interval = setInterval(() => {
console.log(seconds);
seconds--;
if (seconds < 0) {
clearInterval(interval);
console.log('Countdown finished!');
}
}, 1000);
}
countdown(10); // start a 10-second countdown
In this example, we define a countdown()
function that takes a number of seconds as an argument. The function sets up an interval using the setInterval()
method, which calls an anonymous function every second. Inside the function, we log the remaining number of seconds and decrement the counter. If the counter goes below zero, we clear the interval using the clearInterval()
method and log a message indicating that the countdown is finished.
You can customize the behavior of the countdown()
function to meet your specific needs. For example, you can change the interval time to update the countdown more or less frequently, or you can call a different function when the countdown finishes.
Here's an example that uses the setTimeout()
method instead of setInterval()
to run a function after a certain amount of time has elapsed:
function countdown(seconds) {
if (seconds > 0) {
console.log(seconds);
setTimeout(() => countdown(seconds - 1), 1000);
} else {
console.log('Countdown finished!');
}
}
countdown(10); // start a 10-second countdown
In this example, we define a countdown()
function that takes a number of seconds as an argument. If the number of seconds is greater than zero, the function logs the remaining number of seconds and uses the setTimeout()
method to call itself after one second with a decremented number of seconds. If the number of seconds is zero, the function logs a message indicating that the countdown is finished.
How to display an analog clock
To display an analog clock using JavaScript, you can use the built-in Date
object and the HTML canvas
element to draw the clock face and hands. Here's an example:
<canvas id="clock" width="200" height="200"></canvas>
JavaScript code:
const canvas = document.getElementById('clock');
const context = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = canvas.width / 2 - 5;
function drawClock() {
const date = new Date();
const hours = date.getHours() % 12;
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const hourAngle = (hours + minutes / 60) * 30 * Math.PI / 180;
const minuteAngle = minutes * 6 * Math.PI / 180;
const secondAngle = seconds * 6 * Math.PI / 180;
context.clearRect(0, 0, canvas.width, canvas.height);
// Draw clock face
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
context.stroke();
// Draw hour hand
context.beginPath();
context.moveTo(centerX, centerY);
context.lineTo(centerX + Math.cos(hourAngle) * radius * 0.6, centerY + Math.sin(hourAngle) * radius * 0.6);
context.stroke();
// Draw minute hand
context.beginPath();
context.moveTo(centerX, centerY);
context.lineTo(centerX + Math.cos(minuteAngle) * radius * 0.8, centerY + Math.sin(minuteAngle) * radius * 0.8);
context.stroke();
// Draw second hand
context.beginPath();
context.moveTo(centerX, centerY);
context.lineTo(centerX + Math.cos(secondAngle) * radius * 0.9, centerY + Math.sin(secondAngle) * radius * 0.9);
context.stroke();
}
setInterval(drawClock, 1000);
In this example, we use the canvas
element to create a 200x200 pixel clock. We then use the getContext()
method to get a 2D rendering context for the canvas, and we define the center point and radius of the clock face.
Inside the drawClock()
function, we get the current date and extract the hours, minutes, and seconds. We then calculate the angle of each hand in radians and use the cos()
and sin()
functions to calculate the end points of each hand. We use the clearRect()
method to clear the canvas, and then we use the arc()
and lineTo()
methods to draw the clock face and hands.
Finally, we use the setInterval()
method to call the drawClock()
function every second, so that the clock updates in real time.
Note that you can customize the appearance and behavior of the clock by adjusting the canvas
dimensions, the center point and radius of the clock face, and the length and thickness of the hands.
Summary
In this post, we explored various ways to work with dates and times in JavaScript, including getting the current year, date, time, and day of the week; setting and manipulating dates and times; calculating differences between date and time periods; checking how much time has elapsed; doing countdown processing; and displaying an analog clock.
By using the built-in Date
object and various methods it provides, we can perform a wide range of date and time operations in JavaScript, from simple date and time calculations to more complex time-based processing and visualization. Whether you're building a web application, a game, or any other type of software that involves dates and times, JavaScript has the tools you need to work with them effectively and efficiently.