- Time Zone Handling: The `Date` object provides mechanisms for handling time zones, which is crucial when dealing with users from different regions and ensuring that dates and times are displayed accurately and consistently.
In this hands-on, we are going to learn a wide range of functions, each building on what we’ve learned before to give you a solid grasp of working with dates and times. We’ll start by understanding time zones.
As we move forward, we’ll dive into formatting dates, so your date representations look just the way you want them. You’ll also find out how to create custom date formats for specific needs.
Comparing dates will be a breeze as we explore ways to figure out how different dates relate to each other. You’ll get the hang of extracting dates from one another and doing date math, like adding or subtracting time.
- Local Time is the timezone of your computer, where you are currently located.
- UTC is similar to Greenwich Mean Time (GMT).
Now, let’s talk about how to create dates.
Creating a date
You can make a date using `new Date()`. There are four ways to do it:
- With a date-string
- With date arguments
- With a timestamp
- With no arguments
The date-string method
In the “date-string” method, you make a date by giving a date as a string to the new Date function.
We often prefer using date strings to write dates, which feels natural because we’ve used them for a long time.
There’s a clear reason for this.
Date strings can be understood differently in different places. For instance, “10-02-2021” could mean either February 10, 2021 or October 2, 2021. It’s hard to tell which one it is unless you know the specific date format being used.
Here’s what those values mean:
- YYYY: The year in four digits.
- MM: The month is in two digits, where January is 01 and December is 12.
- DD: The date is in two digits, from 0 to 31.
- -: These are the date separators.
- T: It shows the beginning of the time part.
- HH: The hour in 24-hour format, from 0 to 23.
- mm: Minutes from 0 to 59.
- ss: Seconds from 0 to 59.
- sss: Milliseconds from 0 to 999.
- :: These are the time separators.
- Z: If you see Z, it means the date is in UTC time. If there’s no Z, it’s in local time (if time is provided).
You don’t have to specify hours, minutes, seconds, or milliseconds when making a date. For example, to create a date for February 10, 2021, you can simply write:
Creating dates using arguments
- Year: A four-digit number representing the year.
- Month: A number indicating the month of the year (0-11). The first month is represented as 0. If you don’t specify it, it’s assumed to be 0.
- Day: A number representing the day of the month (1-31). If you don’t provide this, it’s set to 1.
- Hour: A number indicating the hour of the day (0-23). If you don’t mention it, it’s set to 0.
- Minutes: A number representing the minutes (0-59). If left out, it’s considered as 0.
- Seconds: A number for the seconds (0-59). If not given, it’s set to 0.
- Milliseconds: A number for the milliseconds (0-999). If not specified, it’s set to 0.
Many developers sometimes steer clear of the “arguments approach” because it might seem complex at first glance. However, it’s simpler than it appears.
Think of it like reading numbers from left to right. As you move from left to right, you insert values in decreasing order of importance: year, month, day, hours, minutes, seconds, and milliseconds.
Here are some additional examples for you to get to know better:
When you create dates using arguments, they are automatically set to your local time, which means the time zone of your computer or device. This can be handy because it avoids confusion between local time and UTC (Coordinated Universal Time). However, if you ever need a date in UTC, you can create one like this:
Creating dates with timestamps
With no arguments
If you make a date with no arguments, you’ll get a date that shows the current time in your local time zone.
Summary of Creating Dates
There are four ways to do it:
- Using a Date String: You can create a date by providing a date string, but it’s not the recommended method.
- Using Timestamps: You can also create dates by providing a timestamp.
- With No Arguments: If you want the current date and time, simply create a date with no arguments.
Next, we’ll learn how to convert a date into a readable string.
Formatting a date
Many programming languages offer a handy way to create custom date formats. In PHP, you can use date(“d M Y”) to format a date as something like “27 Feb 2023.”
The native Date object provides seven formatting methods, and each of these methods gives you a particular value.
Let’s suppose we have a date object as shown in the image below:
Let’s see each of the methods in action.
To have a format that’s just right for you, you’ll have to make it yourself.
Creating your own date format
Suppose you want a date like “Sun, 24 September, 2023”. To make this, you’ll need to understand and use the built-in date methods that come with the Date object.
To obtain dates, you can make use of these four methods:
1. getFullYear: It fetches the four-digit year based on your local time.
2. getMonth: This method retrieves the month of the year, using a numbering system from 0 to 11, where January is 0 and December is 11.
3. getDate: It retrieves the day of the month, ranging from 1 to 31, based on your local time.
4. getDay: This method fetches the day of the week, represented from 0 to 6. The week starts with Sunday as 0 and ends with Saturday as 6.
You can easily obtain “24” and “2023” for “Sun, 24 September 2023” by using the functions getFullYear() and getDate() as shown in the image below.
Getting Sun and September is more challenging.
To get September, you have to make something that connects all twelve months with their names.
Since months are counted starting from zero, we can use an array to represent them.
To find out which month is September, follow these steps:
- Use “getMonth()” to get the month number starting from zero in the date.
- Then, match that month number with the month name in the list of months.
To find the Sun, follow the same steps. This time, you’ll need a list with all seven days of the week.
We need to get the dayIndex with the getDay() method and use the dayIndex to get the day name as shown in the image below.
Next, we need to bring together all the variables we made to create the formatted string. See the image below.
The final code will look something like shown in the image below.
When you want to make a time look exactly how you want it, you can use these methods:
- getHours: It gives you the hours (from 0 to 23) in your local time.
- getMinutes: This one gets you the minutes (from 0 to 59) in your local time.
- getSeconds: It fetches the seconds (from 0 to 59) in your local time.
- getMilliseconds: This one’s for the milliseconds (from 0 to 999) in your local time.
Now, let’s move on to comparing dates.
To find out if one date is earlier or later than another, you can simply use symbols like > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to) to compare them.
Checking if two dates occur at precisely the same time can be tricky. Using “==” or “===” for comparison won’t work in this case.
To see if the two dates are exactly the same, we can compare their timestamps using the “getTime()” method as shown in the image below.
To see if two dates are on the same day, we can compare their year, month, and day values using “getFullYear”, “getMonth”, and “getDate” as shown in the image below.
Getting a date from another date
There are two situations where you might need to work with dates based on other dates:
- Copying a Date/Time: You want to make one date have the same date and time as another date.
- Adjusting by an Amount: You need to change a date by a certain amount, either adding to it or subtracting from it.
Setting a specific date/time
You can change a date or time using these methods:
setFullYear: Change the year (using 4 digits) in your local time.
setMonth: Modify the month of the year in your local time.
setDate: Adjust the day of the month in your local time.
setHours: Update the hours in your local time.
setMinutes: Alter the minutes in your local time.
setSeconds: Change the seconds in your local time.
setMilliseconds: Adjust the milliseconds in your local time.
For example, if you want to make a date fall on the 8th day of the month, you can use setDate(8).
To make the month September, you can use the “setMonth” method. Just remember that months start from zero, not one. So, September would be represented as 8, not 9.
Adding or subtracting a delta from another date
A “delta” simply means a change. When we talk about adding or subtracting a delta from another date, we mean this: you want to figure out a new date that’s a certain amount different from the original date. This difference could be in years, months, days, or any other unit of time.
To calculate this difference, you need to know the current date’s values, which you can find using these methods:
getFullYear: This gives you the year as a four-digit number, according to your local time.
getMonth: It tells you the month of the year, ranging from 0 to 11, based on your local time.
getDate: This provides the day of the month, from 1 to 31, according to your local time.
getHours: It gives you the hour of the day, from 0 to 23, based on your local time.
getMinutes: This tells you the minutes, from 0 to 59, according to your local time.
getSeconds: It gives you the seconds, from 0 to 59, based on your local time.
getMilliseconds: This provides the milliseconds, from 0 to 999, according to your local time.
Let’s assume today is 24th September 2023
To start, we make a fresh Date object.
Next, we need to figure out what we want to modify. In this case, we’re changing days, so we can find out the current day using “getDate()”.
We need to find a date that’s ten days in the future. To do this, we’ll simply add ten days to the current date.
The final code should look as shown in the image below.
Automatic date correction
We started by understanding time zones, which is crucial when dealing with global applications.
Furthermore, we explored formatting dates, ensuring your date representations match your needs. You also discovered how to create custom date formats for specific requirements.
Comparing dates became second nature as we explored ways to figure out how different dates relate to each other. You gained the ability to extract dates from one another and perform date math, like adding or subtracting time.
If you are an aspiring Frontend developer and want to explore more about the above topics, here are a few of our blogs for your reference:
- How to Get the User’s Location Using Mapbox?
Stay tuned to get all the updates about our upcoming blogs on the cloud and the latest technologies.
Keep Exploring -> Keep Learning -> Keep Mastering
At Workfall, we strive to provide the best tech and pay opportunities to kickass coders around the world. If you’re looking to work with global clients, build cutting-edge products, and make big bucks doing so, give it a shot at workfall.com/partner today!