Fully Understand about Date and Time in JavaScript

Fully Understand about Date and Time in JavaScript

JavaScript comes with the built in Date object and related methods. This tutorial will go over how to format and use date and time in JavaScript.

Introduction

Date and time are a regular part of our everyday lives and therefore feature prominently in computer programming. In JavaScript, you might have to create a website with a calendar, a train schedule, or an interface to set up appointments. These applications need to show relevant times based on the user’s current timezone, or perform calculations around arrivals and departures or start and end times. Additionally, you might need to use JavaScript to generate a report at a certain time every day, or filter through currently open restaurants and establishments.

To achieve all of these objectives and more, JavaScript comes with the built in Date object and related methods. This tutorial will go over how to format and use date and time in JavaScript.

Timezones

There are hundreds of timezones in our world. In JavaScript, we only care about two—Local Time and Coordinated Universal Time (UTC).

  • Local time refers to the timezone your computer is in.
  • UTC is synonymous with Greenwich Mean Time (GMT) in practice.

By default, almost every date method in JavaScript (except one) gives you a date/time in local time. You only get UTC if you specify UTC.

With this, we can talk about creating dates.

Creating a date

You can create a date with new Date(). There are four possible ways to use new Date():

  1. With a date-string
  2. With date arguments
  3. With a timestamp
  4. With no arguments

The date-string method

In the date-string method, you create a date by passing a date-string into new Date.

new Date('1988-03-21')

We tend towards the date-string method when we write dates. This is natural because we've been using date strings all our lives.

If I write 21-03-1988, you have no problems deducing it's 21st of March, 1988. Yeah? But if you write 21-03-1988 in JavaScript, you get Invalid Date.

new Date('21-03-1988') returns Invalid Date.

There's a good reason for this.

We interpret date strings differently in different parts of the world. For example 11-06-2019 is either 11th June, 2019 or 6th November 2019. But you can't be sure which one I'm referring to, unless you know the date system I'm using.

In JavaScript, if you want to use a date string, you need to use a format that's accepted worldwide. One of these formats is the ISO 8601 Extended format.

// ISO 8601 Extended format
`YYYY-MM-DDTHH:mm:ss:sssZ`

Here's what the values mean:

  • YYYY: 4-digit year
  • MM: 2-digit month (where January is 01 and December is 12)
  • DD: 2-digit date (0 to 31)
  • -: Date delimiters
  • T: Indicates the start of time
  • HH: 24-digit hour (0 to 23)
  • mm: Minutes (0 to 59)
  • ss: Seconds (0 to 59)
  • sss: Milliseconds (0 to 999)
  • :: Time delimiters
  • Z: If Z is present, date will be set to UTC. If Z is not present, it'll be Local Time. (This only applies if time is provided.)

Hours, minutes, seconds and milliseconds are optional if you're creating a date. So, if you want to create a date for 11th June 2019, you can write this:

new Date('2019-06-11')

Pay special attention here. There's a huge problem with creating dates with date strings. You can spot the problem if you console.log this date.

If you live in an area that's behind GMT, you'll get a date that says 10th June.

new Date('2019-06-11') produces 10th June if you're in a place behind GMT.

If you live in an area that's ahead of GMT, you'll get a date that says 11th June.

new Date('2019-06-11') produces 11th June if you're in a place after GMT.

This happens because the date-string method has a peculiar behavior: If you create a date (without specifying time), you get a date set in UTC.

In the above scenario, when you write new Date('2019-06-11'), you actually create a date that says 11th June, 2019, 12am UTC. This is why people who live in areas behind GMT get a 10th June instead of 11th June.

If you want to create a date in Local Time with the date-string method, you need to include the time. When you include time, you need to write the HH and mm at a minimum (or Google Chrome returns an invalid date).

new Date('2019-06-11T00:00')

Date created in Local Time vsl. Date created in UTC.

The whole Local Time vs. UTC thing with date-strings can be a possible source of error that's hard to catch. So, I recommend you don't create dates with date strings.

(By the way, MDN warns against the date-string approach since browsers may parse date strings differently).

MDN recommends against creating date with date strings.

If you want to create dates, use arguments or timestamps.

Creating dates with arguments

You can pass in up to seven arguments to create a date/time.

  1. Year: 4-digit year.
  2. Month: Month of the year (0-11). Month is zero-indexed. Defaults to 0 if omitted.
  3. Day: Day of the month (1-31). Defaults to 1 if omitted.
  4. Hour: Hour of the day (0-23). Defaults to 0 if omitted.
  5. Minutes: Minutes (0-59). Defaults to 0 if omitted.
  6. Seconds: Seconds (0-59). Defaults to 0 if omitted.
  7. Milliseconds: Milliseconds (0-999). Defaults to 0 if omitted.
// 11th June 2019, 5:23:59am, Local Time
new Date(2019, 5, 11, 5, 23, 59)

Many developers (myself included) avoid the the arguments approach because it looks complicated. But it's actually quite simple.

Try reading numbers from left to right. As you go left to right, you insert values in decreasing magnitude: year, month, day, hours, minutes, seconds, and milliseconds.

new Date(2017, 3, 22, 5, 23, 50)

// This date can be easily read if you follow the left-right formula.
// Year: 2017,
// Month: April (because month is zero-indexed)
// Date: 22
// Hours: 05
// Minutes: 23
// Seconds: 50

The most problematic part with Date is that the Month value is zero-indexed, as in, January === 0, February === 1, March === 2 and so on.

We have no idea why month in JavaScript is zero-indexed, but it is. Rather than argue about why January should be 1 (and not 0), it's better to accept that month is zero-indexed in JavaScript. Once you accept this fact, dates become much easier to work with.

Here are some more examples for you to familiarize yourself:

// 21st March 1988, 12am, Local Time.
new Date(1988, 2, 21)

// 25th December 2019, 8am, Local Time.
new Date(2019, 11, 25, 8)

// 6th November 2023, 2:20am, Local Time
new Date(2023, 10, 6, 2, 20)

// 11th June 2019, 5:23:59am, Local Time
new Date(2019, 5, 11, 5, 23, 59)

Notice dates created with arguments are all in Local Time?

That's one of the perks of using arguments—you won't get confused between Local Time and UTC. If you ever need UTC, you create a date in UTC this way:

// 11th June 2019, 12am, UTC.
new Date(Date.UTC(2019, 5, 11))

Creating dates with timestamps

In JavaScript, a timestamp is the amount of milliseconds elapsed since 1 January 1970 (1 January 1970 is also known as Unix epoch time). From my experience, you rarely use timestamps to create dates. You only use timestamps to compare between different dates (more on this later).

// 11th June 2019, 8am (in my Local Time, Singapore)
new Date(1560211200000)

With no arguments

If you create a date without any arguments, you get a date set to the current time (in Local Time).

new Date()

The time now.

You can tell from the image that it's 25th May, 11:10am in Singapore when I wrote this article.

Summary about creating dates

  1. You can create date with new Date().

  2. There are four possible syntaxes:

  3. With a date string

  4. With arguments

  5. With timestamp

  6. With no arguments

  7. Never create a date with the date string method.

  8. It's best to create dates with the arguments method.

  9. Remember (and accept) that month is zero-indexed in JavaScript.

Next, let's talk about converting a date into a readable string.

Formatting a date

Most programming languages give you a formatting tool to create any Date format you want. For example, in PHP, you can write date("d M Y") to a date like 23 Jan 2019.

But there's no easy way to format a date in JavaScript.

The native Date object comes with seven formatting methods. Each of these seven methods give you a specific value (and they're quite useless).

const date = new Date(2019, 0, 23, 17, 23, 42)
  1. toString gives you Wed Jan 23 2019 17:23:42 GMT+0800 (Singapore Standard Time)
  2. toDateString gives you Wed Jan 23 2019
  3. toLocaleString gives you 23/01/2019, 17:23:42
  4. toLocaleDateString gives you 23/01/2019
  5. toGMTString gives you Wed, 23 Jan 2019 09:23:42 GMT
  6. toUTCString gives you Wed, 23 Jan 2019 09:23:42 GMT
  7. toISOString gives you 2019-01-23T09:23:42.079Z

If you need a custom format, you need to create it yourself.

Writing a custom date format

Let's say you want something like Thu, 23 January 2019. To create this value, you need to know (and use) the date methods that comes with the Date object.

To get dates, you can use these four methods:

  1. getFullYear: Gets 4-digit year according to local time
  2. getMonth: Gets month of the year (0-11) according to local time. Month is zero-indexed.
  3. getDate: Gets day of the month (1-31) according to local time.
  4. getDay: Gets day of the week (0-6) according to local time. Day of the week begins with Sunday (0) and ends with Saturday (6).

It's simple to create 23 and 2019 for Thu, 23 January 2019. We can use getFullYear and getDate to get them.

const d = new Date(2019, 0, 23)
const year = d.getFullYear() // 2019
const date = d.getDate() // 23

It's harder to get Thu and January.

To get January, you need to create an object that maps the value of all twelve months to their respective names.

const months = {
  0: 'January',
  1: 'February',
  2: 'March',
  3: 'April',
  4: 'May',
  5: 'June',
  6: 'July',
  7: 'August',
  8: 'September',
  9: 'October',
  10: 'November',
  11: 'December'
}

Since Month is zero-indexed, we can use an array instead of an object. It produces the same results.

const months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
]

To get January, you need to:

  1. Use getMonth to get the zero-indexed month from the date.
  2. Get the month name from months
const monthIndex = d.getMonth()
const monthName = months[monthIndex]
console.log(monthName) // January

The condensed version:

const monthName = months(d.getMonth())
console.log(monthName) // January

You do the same thing to get Thu. This time, you need an array that contains seven days of the week.

const days = [
  'Sun',
  'Mon',
  'Tue',
  'Wed',
  'Thu',
  'Fri',
  'Sat'
]

Then you:

  1. Get dayIndex with getDay
  2. Use dayIndex to get dayName
const dayIndex = d.getDay()
const dayName = days[dayIndex] // Thu

Short version:

const dayName = days[d.getDay()] // Thu

Then, you combine all the variables you created to get the formatted string.

const formatted = `${dayName}, ${date} ${monthName} ${year}`
console.log(formatted) // Thu, 23 January 2019

Yes, it tedious. But it's not impossible once you get the hang of it.

If you ever need to create a custom-formatted time, you can use the following methods:

  1. getHours: Gets hours (0-23) according to local time.
  2. getMinutes: Gets minutes (0-59) according to local time.
  3. getSeconds: Gets seconds (0-59) according to local time.
  4. getMilliseconds: Gets milliseconds (0-999) according to local time.

Next, let's talk about comparing dates.

Comparing dates

If you want to know whether a date comes before or after another date, you can compare them directly with >, = and <=.

const earlier = new Date(2019, 0, 26)
const later = new Date(2019, 0, 27)

console.log(earlier < later) // true

It's more difficult if you want to check if two dates fall exactly at the same time. You can't compared them with == or ===.

const a = new Date(2019, 0, 26)
const b = new Date(2019, 0, 26)

console.log(a == b) // false
console.log(a === b) // false

To check whether two dates fall exactly at the same time, you can check their timestamps with getTime.

const isSameTime = (a, b) => {
  return a.getTime() === b.getTime()
}

const a = new Date(2019, 0, 26)
const b = new Date(2019, 0, 26)
console.log(isSameTime(a, b)) // true

If you want to check whether two dates fall on the same day, you can check their getFullYear, getMonth and getDate values.

const isSameDay = (a, b) => {
  return a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate()=== b.getDate()
}

const a = new Date(2019, 0, 26, 10) // 26 Jan 2019, 10am
const b = new Date(2019, 0, 26, 12) // 26 Jan 2019, 12pm
console.log(isSameDay(a, b)) // true

There's one final thing we have to cover.

Getting a date from another date

There are two possible scenarios where you want to get a date from another date.

  1. Set a specific date/time value from another date.
  2. Add/subtract a delta from another date.

Setting a specific date/time

You can use these methods to set a date/time from another date:

  1. setFullYear: Set 4-digit year in Local Time.
  2. setMonth: Set month of the year in Local Time.
  3. setDate: Set day of the month in Local Time.
  4. setHours: Set hours in Local Time.
  5. setMinutes: Set minutes in Local Time.
  6. setSeconds: Set seconds in Local Time.
  7. setMilliseconds: Set milliseconds in Local Time.

For example, if you want to set a date to the 15th of the month, you can use setDate(15).

const d = new Date(2019, 0, 10)
d.setDate(15)

console.log(d) // 15 January 2019

If you want to set the month to June, you can use setMonth. (Remember, month in JavaScript is zero-indexed!)

const d = new Date(2019, 0, 10)
d.setMonth(5)

console.log(d) // 10 June 2019

Note: The setter methods above mutate the original date object. In practice, we should not mutate objects (more on why here). We should perform these operations on a new date object instead.

const d = new Date(2019, 0, 10)
const newDate = new Date(d)
newDate.setMonth(5)

console.log(d) // 10 January 2019
console.log(newDate) // 10 June 2019

Adding/Subtracting delta from another date

A delta is a change. By adding/subtracting delta from another date, I mean this: You want to get a date that's X from another date. It can be X year, X month, X day, etc.

To get a delta, you need to know the current date's value. You can get it using these methods:

  1. getFullYear: Gets 4-digit year according to local time
  2. getMonth: Gets month of the year (0-11) according to local time.
  3. getDate: Gets day of the month (1-31) according to local time.
  4. getHours: Gets hours (0-23) according to local time.
  5. getMinutes: Gets minutes (0-59) according to local time.
  6. getSeconds: Gets seconds (0-59) according to local time.
  7. getMilliseconds: Gets milliseconds (0-999) according to local time.

There are two general approaches to add/subtract a delta. The first approach is more popular on Stack Overflow. It's concise, but harder to grasp. The second approach is more verbose, but easier to understand.

Let's go through both approaches.

Say you want to get a date that's three days from today. For this example, let's also assume today is 28 March 2019. (It's easier to explain when we're working with a fixed date).

The first approach (the set approach)

// Assumes today is 28 March 2019
const today = new Date(2019, 2, 28)

First, we create a new Date object (so we don't mutate the original date)

const finalDate = new Date(today)

Next, we need to know the value we want to change. Since we're changing days, we can get the day with getDate.

const currentDate = today.getDate()

We want a date that's three days from today. We'll use add the delta (3) to the current date.

finalDate.setDate(currentDate + 3)

Full code for the set approach:

const today = new Date(2019, 2, 28)
const finalDate = new Date(today)
finalDate.setDate(today.getDate() + 3)

console.log(finalDate) // 31 March 2019

The second approach (the new Date approach)

Here, we use getFullYear, getMonth, getDate and other getter methods until we hit the type of value we want to change. Then, we use create the final date with new Date.

const today = new Date(2019, 2, 28)

// Getting required values
const year = today.getFullYear()
const month = today.getMonth()
const day = today.getDate()

// Creating a new Date (with the delta)
const finalDate = new Date(year, month, day + 3)

console.log(finalDate) // 31 March 2019

Both approaches work. Choose one and stick with it.

Automatic date correction

If you provide Date with a value that's outside of its acceptable range, JavaScript recalculates the date for you automatically.

Here's an example. Let's say we set date to 33rd March 2019. (There's no 33rd March on the calendar). In this case, JavaScript adjusts 33rd March to 2nd April automatically.

// 33rd March => 2nd April
new Date(2019, 2, 33)

33rd March gets converted to 2nd April automatically.

This means you don't need to worry about calculating minutes, hours, days, months, etc. when creating a delta. JavaScript handles it for you automatically.

// 33rd March => 2nd April
new Date(2019, 2, 30 + 3)

30 + 3 = 33. 33rd March gets converted to 2nd April automatically.

And that's everything you need to know about JavaScript's native Date object.

Conclusion

Knowing how to work with dates is essential for many common tasks in JavaScript, as this can enable you to do many things from setting up a repeating report to displaying dates and schedules in the correct time zone.

Thank you for reading !

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

JavaScript is the programming language of HTML and the Web. JavaScript is easy to learn. This tutorial will teach you JavaScript from basic to advanced. JavaScript Programming Tutorial - Full JavaScript Course for Beginners

Watch this JavaScript tutorial for beginners to learn JavaScript programming from scratch. 👍

⭐️Course Contents⭐️

01 | Introduction

Get an introduction from Bob, as he kicks off the course, sets expectations, and gives you a little guidance for the road ahead.

02 | Setting Up the Development Environment

See how to install Node and Visual Studio Code, and learn why you need each. Watch as Bob writes a first tiny line of code to make sure that the installation is ready.

03 | Basic JavaScript Syntax

Hear about the basics of the JavaScript syntax, including how JavaScript is executed, how to create a properly formed statement, and more.

04 | Variables

Learn what variables are and how to declare, initialize, set, and get values from them.

05 | Data Types

JavaScript works with data types differently than other programming languages do. Learn from Bob as he explains some of the most basic data types and how to determine the type held by a variable.

06 | Type Coercion and Conversion

Sometimes you need to explicitly convert the data type of a value into a different data type. Sometimes JavaScript will do this automatically for you. Bob explains how and why this happens.

07 | Expressions and Operators

Learn how to spot a well-formed expression and how to compose expressions through the combination of operators and operands.

08 | Arrays

Watch as Bob demonstrates how to use arrays, how to add/remove elements of an array, how to access elements of an array using the index, how to get the number of elements in an array, and more.

09 | Function Declaration

Get an introduction to functions, as Bob shows you one way to define a function, how to call the function, how to pass parameters into a function, how to return values from a function, and more.

10 | Function Expressions

Sometimes a function declaration is more than you need. Get details in this lesson, as Bob demonstrates how to use a function expression and how to create an immediately invoked function expression.

11 | Decision Statements

Learn how to add logic to your applications by testing conditions using if / else statements, switch / case statements, and the ternary operator.

12 | Iteration Statements

Watch as Bob introduces the For and While statements, which enable you to loop through lists of values and perform operations on them.

13 | Basics of Scope

Hear an explanation of the notion of the lifetime of variables and their reach into other code blocks, in this discussion of scope.

14 | Returning Functions from Functions

As a building block toward a more sophisticated approach to building JavaScript applications, see how you can return functions from functions.

15 | Object Literals

Objects contain properties and functions that describe attributes of the object and its behavior, respectively. Watch as Bob demonstrates how to create object literals.

16 | Module Pattern and Revealing Module Pattern

Learn how to introduce variables and functions without leaving an unnecessarily large footprint on the global scope.

17 | Closures

Closures allow developers to bind functions to their execution context, including variables, so you can build specialized versions of functions. Learn how closures work and how to create them.

18 | this Keyword

Get the details on the "this" keyword, which causes a lot of confusion for JavaScript developers. Listen as Bob explains what this mysterious object is and how to bend it to your will.

19 | Destructuring

See how to use destructuring, a new feature in JavaScript that allows you to unpack array elements or object properties in a concise syntax.

20 | String Template Literals

Learn about the new string template literal syntax to enable string interpolation, multi-line string formatting, and more.

21 | Regular Expressions

Working with string data, Bob explains how use regular expressions to determine such things as whether a string matches a specific pattern or whether an instance of the pattern exists in a string.

22 | Built-In Natives

Join Bob as he examines native, built-in JavaScript functions that return objects that box the primitive types in order to provide additional helper methods on your values.

23 | Constructor Function Calls with the new Keyword

Learn how constructor functions work, see how to make key distinctions in what they are, and find out why they’re helpful.

24 | Objects and the Prototype Chain

Moving past the absolute beginner matter, listen in as Bob explains how objects work in JavaScript and how you can create an object that is linked to another object.

25 | JavaScript Classes

Bob demonstrates how “syntactic sugar” works on top of the existing functions and prototype chaining to help JavaScript resemble more traditional object-oriented programming languages.

26 | Arrow Functions

The latest version of JavaScript added arrow functions, a shorthand syntax for creating functions. Watch as Bob demonstrates how to create them and shows where they’re useful.

27 | Truthy and Falsy Values

Listen is as Bob circles back to topics that are important (but didn’t easily fit into earlier topics) and looks at the odd way in which JavaScript evaluates certain expressions as truthy and falsy.

28 | null Type

Similar to the undefined primitive type, the null type represents a variable that has no reference to an object when one was expected. Hear an explanation of how and why we should think about nulls.

29 | Date Objects

No discussion of JavaScript would be complete without understanding the Date built-in native function which provides properties and methods for working with dates and times.

30 | String Methods

The built-in native String function provides several very useful methods for manipulating and evaluating strings. Watch Bob demonstrate how to use a few of the most useful ones.

31 | Array Methods

We’ve worked with arrays throughout this course. Now Bob takes a few minutes to show you some of the most useful methods provided by the Array built-in native function.

32 | Error Handling with Try Catch

See how to wrap a try/catch/finally statement around potentially problematic code to anticipate everything that could go wrong with it, and learn other error-handling tips.

33 | Understanding the Document Object Model

Watch Bob examine the web browser environment and how it creates an object graph of nodes that represent elements, their attributes, and text, plus how to properly attach your code to an HTML page.

34 | Working with DOM Nodes

Continuing from the previous video, Bob demonstrates a slightly more compelling example that helps us understand how to manipulate, create, and delete element nodes and attribute nodes.

35 | Course Conclusion

In this final video, Bob briefly adds some closing comments and well wishes. You can also optionally complete a survey to provide insight into how Microsoft can improve this course.

Thanks for watching

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Functional Programming for JavaScript Developers

Functional Programming for JavaScript Developers

Functional Programming for JavaScript Developers. Learn Functional Programming and how it enables developers to move from imperative to declarative programming. Solidify your knowledge of functional JavaScript programming, including objects, arrays, and prototypes. Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript. Learning how to build and manage asynchronous functional programs is perhaps the most important part of becoming an effective JavaScript programmer.

Functional Programming for JavaScript Developers

Learn functional programming and how it enables developers to move from imperative to declarative programming

Improve your code with functional patterns like pure functions, compose & map/reduce/filter...plus advanced concepts like fusion, transducing and monads!

Solidify your knowledge of functional JavaScript programming, including objects, arrays, and prototypes

Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript. Go beyond the fundamentals of asynchronous JavaScript and use features and techniques that will help you reduce code and create smarter applications.

Learning how to build and manage asynchronous functional programs is perhaps the most important part of becoming an effective JavaScript programmer.

What you'll learn

  • On the surface, this course is designed for beginning and intermediate JS developers who want to learn the fundamentals in order to understand and use functional programming in both ES5 and ES6. However, this course is also perfect for people preparing to enter into competitive JavaScript bootcamps

Programming a Javascript Simon Game Tutorial

Programming a Javascript Simon Game Tutorial

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

For those who don't know, I'm a full stack web developer who has been in the industry for over 5 years now. There is a lot of things I have learned along the way and I'd like to share that knowledge with anyone wanting to learn!

like this video if you found it useful and would like to see more videos of the same content.

subscribe to my channel if you are trying to improve your abilities as a web developer, software engineer, or even if you are just learning to code.

Don't forget to turn on those bell notifications!