Technology

How one can edit the date and time in JavaScript

In theory, treating data as a developer is as easy as creating, storing, and possibly editing data. However, as a JavaScript developer, you know that this theory holds true not long after you start working with real data. In addition to different date and time formats, you need to consider the time zone and local differences.

For this reason, many JavaScript developers seek help from third-party libraries when they need to manage data in an application. While these libraries reduce the complexity of the task, having a clear understanding of how to deal with vanilla JavaScript data has its advantages.

This tutorial will introduce you to working with dates in vanilla JavaScript, as well as useful third-party libraries to make more complex date-related tasks easier.

JavaScript date object

The Date object in JavaScript is the main element in handling the date and time. A single point in time is recorded when the number of milliseconds has passed since 00:00:00 UTC on January 1, 1970. This date / time combination is known as epoch time. For JavaScript, this is the beginning of the time in the world.

Create appointments

You can easily create a date with new date() . You can pass parameters to the date constructor to create a date of your choice. The specified parameter can take various forms.

Pass in a date string

You can pass a date string of an accepted format when creating a new date object.

const date = new date (“2020-12-31”);

If we now print the creation date, this will be indicated.

Thu 31.12.2020 01:00:00 GMT + 0100 (Central European Standard Time)

In addition to the date we passed in, the date object has more values, including a time and a time zone. Since we didn’t specify a specific value for these parameters when we created the object, JavaScript uses the local time and the code system’s time zone.

If we want to pass the time or time zone with the parameter string, we can use a format like this.

YYYY-MM-DDTHH: mm: ss.sssZ

  • YYYY: year
  • MM: month (1 to 12)
  • DD: date (1 to 31)
  • HH: hour in 24-hour format (0 to 23)
  • mm: minutes (0 to 59)
  • ss: seconds (00 to 59)
  • sss: milliseconds (0 to 999)
  • T is used to separate the date and time in the string
  • When Z is present, the time is assumed to be in UTC. Otherwise local time is assumed.

However, if T and Z are absent, the date the string was created can produce different results in different browsers. In this case, add to always have the same time zone for the date + HH: mm or -HH: mm until the end.

You can get the same results with that Date.parse Function instead of passing the date string to the date constructor. Date.parse is called indirectly in the constructor when you pass a date string.

The format used in these strings is the ISO 8601 extended calendar format. For details, see the ECMAScript specification .

Pass date arguments

You can pass the date arguments directly to the date constructor without using confusing date strings. The order and length of each year, month, and so on is exactly the same as a date string.

If we check the result of the created date, we can see a crucial difference in the final date.

What’s weird? In creating the date, we used 9 for the month we can assume to be September. When we print the result, the month is October instead. Why is that?

JavaScript uses a zero-based index to identify each month in a year. This means that for JavaScript, January is represented by 0 instead of 1. Likewise, October is represented by 9 instead of 10.

With this method of creating a date, we cannot pass an argument to specify its time zone. Therefore, the system’s local time is used by default. But we can use that Date.UTC Function to convert the date to UTC before it is passed to the date constructor.

Pass in a timestamp

Remember, I mentioned that JavaScript stores the elapsed time since the epoch in the Date object. We can pass this elapsed time value, called a timestamp, to indicate the date we’re creating.

Create a date object for the current date and time

If you want to create a date object for the current system date and time, use the date constructor without passing an argument.

You can use that too Date.now () Function for the same task.

Formatting data

JavaScript has several built-in functions for formatting a date. However, these functions only convert the date into a format specific to each format.

Let’s see how each formatting function works.

Internationalization API

ECMAScript Internationalization API Allows a date to be formatted in a specific locale using the Intl object.

You can pass an option object to the DateTimeFormat function to display time values ​​and customize the output.

Custom date formats

If you want to format the date in a different format than what these features provide, you must do so by accessing and combining each part of the date separately.

JavaScript provides the following functions for getting the year, month, date, and day from a date object.

Now you can convert the date to a custom format using the retrieved parts.

Update data

JavaScript offers various methods for editing a date that has already been created.

Compare data

If you want to know whether a certain date is before another, you can directly use operators that are greater or less than to compare.

This is because dates are objects in JavaScript, so each date has a different instance of the class == or === The operator compares the memory address instead of the actual values ​​of the data.

JavaScript date manipulation libraries

We can find various JavaScript libraries for manipulating date and time as open source projects or in other ways. Some of them are designed for all types of date and time manipulation, while others have specific use cases. In this section, I’m only going to talk about popular multipurpose libraries.

Moment.js was the king of date manipulation libraries among JavaScript developers. However, its developers recently announced that it focuses on keeping the current code base rather than adding new functionality. They recommend looking for an alternative solution for those working on new projects.

So, other than Moment.js, what libraries can we use to make our life as developers easier?

Date fns

Date fns in an open source library that supports date analysis and formatting, locales, and date arithmetic such as addition and subtraction. Because of its versatility, it is known as the Lodash for dates.

Luxon

Luxon is a date / time manipulation library created by one of the developers of Moment.js to suit modern application needs. Similar to Date-fns, Luxon offers data formatting and analysis functions. It also offers native Intl support and can be linked.

Summary

This tutorial explained how to work with date and time in JavaScript with and without external libraries. Working with dates is always painful in almost (if not all) programming languages. Fortunately, JS and its library ecosystem do all of the heavy lifting for us, so we can focus on creating functions.

These items was originally published on Live code stream by Juan Cruz Martinez (Twitter: @bajcmartinez), Founder and publisher of Live Code Stream, entrepreneur, developer, author, speaker and maker of things.

Live code stream is also available as a free weekly newsletter. Sign up for updates on everything related to programming, AI and computer science in general.

Read on: Schools of robotic fish could soon monitor our oceans for environmental threats

Leave your vote

0 points
Upvote Downvote

Related Articles

Log In

Forgot password?

Forgot password?

Enter your account data and we will send you a link to reset your password.

Your password reset link appears to be invalid or expired.

Log in

Privacy Policy

Add to Collection

No Collections

Here you'll find all collections you've created before.