JavaScript Date and Time Simplified

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript Date and Time Simplified

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Basics

const today = new Date();

console.log(today.toString());
// Fri Mar 10 2023 17:39:33 GMT+1100 (Australian Eastern Daylight Time)

console.log(today); // 2023-03-10T06:39:33.953Z

console.log(today.toISOString()); // 2023-03-10T06:39:33.953Z

const date_2025_jan_1_13_30_15 = new Date(2025, 0, 1, 13, 30, 15);

console.log(date_2025_jan_1_13_30_15); // 2025-01-01T02:30:15.000Z

console.log(typeof today); // 'object'

console.log(today instanceof Date); // true

Formatting Dates

/** Local New Year 2050 */
const date = new Date(2050, 0, 1, 0, 0, 0);

/// Mission: format as YYYY-MM-DD hh:mm:ss

function padZero(num) {
return num < 10 ? `0${num}` : num.toString();
}

/** date => 'YYYY-MM-DD hh:mm:ss' */
function format(date) {
const YYYY = date.getFullYear().toString();
const MM = padZero(date.getMonth() + 1);
const DD = padZero(date.getDate());
const hh = padZero(date.getHours());
const mm = padZero(date.getMinutes());
const ss = padZero(date.getSeconds());
return `${YYYY}-${MM}-${DD} ${hh}:${mm}:${ss}`;
}

console.log(format(date));

timestamp

// I'm in UTC+11
const date = new Date(2030, 0, 1, 11);
console.log(date); // 2030-01-01T00:00:00.000Z

const timestamp = date.getTime();
console.log(timestamp); // 1893456000000

const copy = new Date(timestamp);
console.log(copy); // 2030-01-01T00:00:00.000Z

/** Move behind by 24 hours */
const yesterdayTimestamp =
timestamp - 24 * 60 * 60 * 1000;
const yesterday = new Date(yesterdayTimestamp);
console.log(yesterday); // 2029-12-31T00:00:00.000Z

Timezone

// Hint: we are +11 time zone
// Default inputs are in local time
const date_2025_jan_1_11am_australia = new Date(2025, 0, 1, 11);
// Time is absolute, default representation is UTC
console.log(date_2025_jan_1_11am_australia); // 2025-01-01T00:00:00.000Z

// In local its 11 hours
console.log(date_2025_jan_1_11am_australia.getHours()); // 11
// In UTC its 00 hours
console.log(date_2025_jan_1_11am_australia.getUTCHours()); // 0

// UTC version
const date_2025_jan_1_midnight_utc = new Date(Date.UTC(2025, 0, 1, 0));
console.log(date_2025_jan_1_midnight_utc); // 2025-01-01T00:00:00.000Z

const minuteOffsetLocalTimeZone = new Date().getTimezoneOffset();
// offset = (UTC - LOCAL) minutes

// We are +11 hours => 11*60 = 660 minutes ahead of UTC
console.log(minuteOffsetLocalTimeZone); // -660

/** Time zone offset formatted as `(+/-)hh:m` */
function formattedTimezone() {
const offset = new Date().getTimezoneOffset();
const sign = offset > 0 ? "-" : "+";
const minutes = Math.abs(offset % 60);
const hours = Math.floor(Math.abs(offset / 60));
return `${sign}${hours}:${minutes}`;
}

console.log(formattedTimezone()); // +11:0

now

Example use case of performance testing:

let timestamp;

timestamp = new Date().getTime();

timestamp = Date.now();

console.log(timestamp); // 1678435753900

function measure(approach, cb) {
const start = Date.now();
for (let index = 0; index < 100_000; index++) cb();
const end = Date.now();
console.log(approach, 'took', end - start, 'ms');
}

const size = 10_000;

console.log('🏎️');
measure('fill', () => {
Array(size).fill();
});
measure('spread', () => {
[...Array(size)];
});
console.log('🏁');

toJSON

// we are in UTC +11
const year2049 = new Date(2049, 0, 1, 11);

console.log(year2049.toString());
// Fri Jan 01 2049 11:00:00 GMT+1100 (Australian Eastern Daylight Time)
console.log(year2049.toISOString()); // 2049-01-01T00:00:00.000Z
console.log(year2049.toJSON()); // 2049-01-01T00:00:00.000Z

const dateFromString = new Date('2049-01-01T00:00:00.000Z');
console.log(dateFromString); // 2049-01-01T00:00:00.000Z
console.log(dateFromString.toString());
// Fri Jan 01 2049 11:00:00 GMT+1100 (Australian Eastern Daylight Time)

const bladeRunner = {
year: new Date(2049, 0, 1, 11)
};

const json = JSON.stringify(bladeRunner);
console.log(json);
// {"year":"2049-01-01T00:00:00.000Z"}

const movie = JSON.parse(json);
console.log(movie.year); // '2049-01-01T00:00:00.000Z'
movie.year = new Date(movie.year);
console.log(movie.year.toString());
// Fri Jan 01 2049 11:00:00 GMT+1100 (Australian Eastern Daylight Time)
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

JavaScript comes with a built-in date class that we can use to manage daytime values. We can create a new instance of the date object by using the date constructor. If we don't pass it any arguments, it's going to get initialized to the current date. For example, this particular piece of code is running on Friday 10th, March, 2023. If we use the date two stringing method, it renders it out in the current time zone, but the date itself is actually independent of any time zone and it is a particular point in time. It is actually tracked from U T C and if we log it out by itself, we can see the U T C equivalent of this particular date value.

00:34

Since we are in G M T plus 11, the 5:00 PM is going to be equivalent to 6:00 AM in U T C. Now this particular string that we are looking at is called the TZ string as indicated by the presence of a T and a Z. Everything before the T is the ear month and day, and after that we have the R minute, seconds and milliseconds followed by the Z. The TZ string is actually an IO standard, so the date object also comes with a function called two io o string, which actually gives us the string. That console log is logging out the date.

01:09

Constructor also accepts values in the local time zone so we can initialize a new local date and here we are initializing a new local date for the EA 2025, January 1st with the Rs minutes and seconds at 1330 and 15. This constructor should make obvious sense except for the one thing that you should always remember, which is that month within JavaScript is tracked with index zero, so January is going to be zero as we are seeing over here, and December is going to have the value 11. The values that we are providing over here are in the local time zone, so the R 13 for GMT plus 11 is going to be the UTC two,

01:46

which is what we will see when we log this value out without applying any formatting or using the two stringing function. Just like other JavaScript objects created from JavaScript classes, the type of operator for this will give us the string object and if you want to check if a particular object is an instance of date, we can use the built-in instance of operator and of course today is an instance of date. The date object provides various methods to access its sub-components, which can be used to format the date to our liking. As an example, consider the new air 2050 in local time zone.

02:20

Our mission should be choose to accept it is to display the date in local time zone with the format Y Y M M D D R R, minute, minute, second. Second. Now, in order to pad the different values, for example, the day one to become a zero one, we are going to create a nice utility function that looks at the number. If it is less than 10, then it pads a zero before it, otherwise it simply converts it to a string. With this simple utility in place, let's start creating our format function. Our function will take the date object and format it to the desired string. First up,

02:53

we can get the four digit ear from the date object by using the get full year method and then we convert this numeric value to a string by simply using two string. Next we are going to generate the month as mm, and for that we use the date get month function and as you mentioned, the month is returned with a zero waste index, so we need to increment it by one for a more human presentable format. Once we have that value, we rapid without pad zero utility. The remaining portions of our format are going to be pretty easy. They are simply going to be padded zero versions of the get date for the day, the get rs for the R get minutes for the minutes and get seconds for the

03:31

seconds. Once we have these values, the final result is going to be simply a concatenation of these into a nice string that gives us the desired format. Let's verify that this function behaves the way that we want by using the date value that we have, passing it to format and then logging that out to the console. And if you run this code, you can see that it matches our expectations. We created a date in local time zone for 2050 new year and we get that presented out in the desired format for the user. A programming term worth knowing is epoch. It is the absolute point in time, which is midnight January 1st, 1970 at U T C zero.

04:08

A key way that developers interact with dates is a milliseconds since epoch and this millisecond value is also called Unix time and also called the timestamp. I want to point out the time in U T C plus 11. So here I am creating the new year 2030 plusing in the R 11, so it is indeed zero zero in U T C I can get the timestamp for this value by using the built in date get time method. We can actually create a new instance of the date by using this timestamp. Unlike the year, month, day version of the constructor, when we only pass in the timestamp,

04:41

the timestamp number by itself is by definition from U T C and the date constructor accepts it as U T C as well. So irrespective of what your machine time zone is, if you use the same number, you will get exactly the same string, which is 2030 new year. At U T C. A key use case for the timestamp value is that it allows you to do date math quite easily. As you mentioned, the timestamp value is in milliseconds, so if you wanted to calculate what date it would be one day before the new year 2030, we can actually do that by calculating a new timestamp and subtracting the

05:16

required number of milliseconds for 24 hours. Once we have this new timestamp, we can pass it to the date constructor and now of course we can look at what that value is going to be. And of course it is going to be 2029 December 31st. The JavaScript date object transparently accepts and presents values in the local time zone, but it also provides some utilities to create dates in U T C time and provide information about the local time zone. Here I'm creating a date in the local time zone for 2025 New year at 11:00 AM of course, since I'm at plus 11,

05:50

using the R 11 gives us midnight. At U T C, we can get the RS in the local time zone as we saw when we were doing data formatting by using the built-in get RS method. And of course for this particular time the local RSS would be 11. The data object actually also provides US methods to get the U T C version of this time. For example, we can get the U T C Rs and of course for this particular time it's going to be zero, just like get ours is local and get U T C R is the U T C version. We have U T C versions of the other formatting functions as well. For example, get U T C date, get U T C minutes, get U T C seconds. As we can see,

06:27

the date constructed takes values in the local time zone, but we can actually create a date at A U T C point in time as well by using the builtin date UTC static method. This method takes the same values as the date constructor, however it accepts them at U T C time zone. So here we are creating a date at U T C R zero. This method also only returns a timestamp and does it actually create a date object, but as we know, we can convert a timestamp to a date object quite easily by passing it to the date constructor. Now time is absolute,

06:59

and actually this is the same point on the dimension of time as R 11 in our local time. So if we log it out, you can see that it is the same value as the one we created before. In addition to allowing us to create time in U T C values transcript also offers us a simple method to get the time zone offset. Compared to U T C, there is a method called get time zone offset offered by the date object that gives us the difference of U T C minus local in minutes. Since we are in time zone plus 11, local is going to be ahead by 11 hours or 6, 6 0 minutes and

07:35

therefore the minute offset local time zone is going to be minus 6 6 0. Use this value however you see fit. For example, let's just create a formatting function that displays the current time zone. In plus or minus RR minute, we start off by creating a new data object and capturing the result of get time zone offset. If the offset is greater than zero, it means that local is less than U T C and therefore we will use minus. Otherwise we will use the plus sign. The minute remainder after we remove the RS would simply be the absolute value of the offset remainder 60. And for the R value,

08:10

we will simply divide by 60, take the absolute and then use math flow to get rid of the remainder as that is already accounted for by the minutes. With these values in place, we simply return the formatted string sign S colon minutes, and now for the moment of truth, if we log out the formatted time zone for the current time zone of plus 11, we should see plus 11 colon zero. And if we run this code, you can see that it matches our expectations. The date class comes with a static now method that provides the current numeric timestamp and a common use case for this function is simple timing or

08:45

performance testing. We've looked at timestamps before and we know that we can get the current timestamp by creating a new date object and using the get time method. The Date object comes with a static now method that does exactly the same thing but with lesser neater code. And of course the value of the timestamp is the number of milliseconds since epoch the date. Now method gives us convenient access to the number of milliseconds at the current point in time. So let's use it to create a nice utility function that can be used to measure the performance of a particular callback function.

09:18

We take an approach string for logging and then a callback function. We start off by noting the current milliseconds using date now and then we run through a loop for a hundred thousand times each time invoking the past in callback. After this loop terminates, we note on the milliseconds again by using data now and now we have the start and the end and we simply log out the approach took N minus start milliseconds. For our example, we will compare the performance of the various ways you can create nont arrays of size 10,000. We kick off our test by first logging the race car.

09:54

One approach to creating a non empty array is to pass the size to the array function and then use the fill method. Array size creates an empty array with empty slots which cannot be used for iteration and working the fill method fills those slots up with undefined. So we can use functions like for each and map. Another approach to creating an non empty array is to first create that empty array with array size and then using the built-in spread operator. Finally, after both of these functions return, we will log out the racing flag. Now let's kick it off and see which one wins. On my machine fill takes about 1.7 seconds and spread takes about

10:31

1.4 seconds and I've tested it on other machines as well. Spread is always faster than fill and this is one of the reasons why in our JavaScript lesson on arrays, we recommended that we use the spread operator to create non empty arrays. How JavaScript dates get serialized by Jason is actually quite nice and it makes sending and displaying date values across devices in different regions. Quite simple. For user interface purposes, let's create a date in our local time zone of U T C plus 11 for 2049. January 1st are 11. Now of course if we log it out in our local time zone,

11:06

you can see that it is 11:00 AM on January 1st, 2049, but we can also get the ISO version of the state, which is always going to be normalized to U T C and of course at plus 11 in our time zone at U T C, it is going to be R zero. The JavaScript date object also overrides the two JSON method to do exactly the same thing as the two ISO string method. This means that when JavaScript serializes the date object to json, all dates get serialized to U T C TZ date strings and in reverse we can actually create a date from the TZ date string as well.

11:42

So here is that same point in time and of course if you log it out, that is what we see. But if we use the two stringing method, we get that value formatted for the local time zone, which of course is going to be be 11:00 AM. Now that we are familiar with the two js method that gives us the TZ string and the date constructed that accepts that t Z string. Let's look at a JSON example. We create an object blade runner that has a property here that points to the date 2049 New Year at 11:00 AM in the local time zone. If you want to send it off to a server using json, we can use JSON string gify and this gives us a string such that the ear is

12:18

going to point to the TZ string that we saw before. There is no ambiguity about this particular point in time because it is always in U T C and it doesn't matter where the server is located or where the user sent it from. On the flip side, when the server sends it out to someone, we would use adjacent do pass to pass it into an object. And of course this particular string value is going to get serialized to a string, but we can convert it to a date object quite easily by passing the string to the date constructor. And now we have a date object that points to the same absolute point in time and we can render it out however we want. For example,

12:53

when we render it out using two stringing, it renders it in the local time zone and of course, because we are 11 hours ahead, the user's perception of the time over here would be 11:00 AM In case you have a notice, I do have a passion for time because after all time is the most valuable asset that we have. As always, thank you for spending your time with me and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36