Changing date formats in javascript

How to Change the Date Format in JavaScript

Sajal Soni

Sajal Soni Last updated Dec 26, 2021

In this article, we’ll see how you can change the format of a date in JavaScript. We’ll go through a couple of real-world examples to demonstrate how you can convert a date from one format to another in JavaScript.

JavaScript is one of the core technologies of the web. The majority of websites use it, and all modern web browsers support it without the need for plugins. In this series, we’re discussing tips and tricks to help you in your day-to-day JavaScript development.

For date and time, JavaScript provides the built-in Date object, which primarily represents the current date and time in the timestamp format. The Date object also allows you to initialize a specific date, which is in one of the standard formats. Once you instantiate a Date object, it provides several utility methods that allow you to get various components of the date and time, and you can use these various methods to format a date in different ways.

Читайте также:  Source file code html

However, when it comes to changing a date from one format to another, there’s no straightforward way to convert a date to your desired format. In this article, I’ll show you how to build a utility function, which allows you to convert a date from one format to another. At the end, we’ll also discuss a popular third-party library that allows you to change a date into different formats.

How to Change the Date Format in Vanilla JavaScript

In this section, we’ll build an example which allows you to change the date format in JavaScript.

Let’s have a quick look at the following example.

As you can see, we’ve implemented the dateFormat function, which takes two arguments. The first argument is the source date, and the second argument is the desired date format to which the source date will be converted. It’s important to note that the second argument must be a valid date format containing «dd» , «MM» , and «yy» or «yyyy» .

Now, let’s go through the dateFormat function. Firstly, we’ve instantiated the Date object by passing the source date as the first argument of the constructor.

Next, we’ve used the getMonth , getDate() , and getYear() methods of the Date object to get the date components. It’s important to note that the month value starts with zero, so we have to increment the value by one to get the actual month. We’ve also used the padStart method to format the month value with a leading zero if it’s needed. We do something similar with the year and day values.

With everything in place, you should be able to convert a date to your desired format.

When it comes to date manipulation in JavaScript, there are a lot of third-party libraries available. Some of the most popular options are Moment.js and Day.js. When it comes to formatting a date into a custom format, these libraries are really easy to use.

Let’s have a quick look at the Moment.js example to understand how it works.

As you can see, it’s fairly easy to convert a date into different formats with the use of this third-party library.

Conclusion

Today, we looked at a couple of ways to change a date from one format to another format in JavaScript: a custom function and a third-party library.

Источник

Javascript Change Date Format

Javascript Course - Mastering the Fundamentals

Javascript is a widely use web technology that is being used to build website all over. It is supported by all the browsers and that makes it easily ready to use. The built in functions in Javascript without requiring the set up for plugins makes it Developer friendly.

Introduction

To format a date string to another desired format, we build an utility function that helps us to convert a date to a another format. There are some javascript libraries that allow us to convert and format and change date format in javascript date string. We will use the Date object that represents the date and time in the form of a timestamp and then we will use various method to format date string on several ways.

Change Date Format Using Date() in JavaScript

Date() is a built in Javascript function that returns a formatted date string. The function new Date() when called returns the Date object and works like a constructor.

Let us consider a Javascript program to understand the use of Date()

Explanation: Here, the above Javascript function new Date() returns the Date object and we get the formatted string as day/ month(in string format) and year. Date() works like a constructor.

Change Date Format Using DateJS in JavaScript

DateJS is a library for Date provided by Javascript that is used to format, change date format in javascript,process and parse a string. To import Date.js include the .js file from the /build/ folder.

We use Date.parse to parse a string using DateJS in JAvascript.

Examples

Change Date Format yyyy-mm-dd hh:mm in JavaScript

The function described below converts a string in yyyy-mm-dd format to hh:mm format.

Explanation: The above JAvascript function stores the Date() in current date variable and converts it into a formatted date and returns the date in hh:mm format.

Convert dd/mm/yyyy to mm/dd/yyyy in JavaScript

The below mentioned javascript function converts dd/mm/yyy string format to mm/dd/yyyy format.

Explanation: The above function uses date.split(«/») to format a dd/mm/yyyy to mm/dd/yyyy format.

Beautify Date yyyy-mm-dd hh:mm in Month Name and Day Name Format

Let us consider a Javascript function that converts a month number to month name format.

How to Change the Date Format in Vanilla JavaScript?

Let us understand how to change the Date Format using Vanilla Javascript.

Explanation: Here we use the dateFormat function consisting of two arguments- the input Date and the format to which the input Date is to be converted. The Date object is initialised when the source Date is passed as an argument to the constructor.

DateMethods like getMonth() , getDate() and getYear() are used to get the Date format components.

To format a month with a zero leading it’s value, we use the method padStart .

Conclusion

In this article, we learnt.

  • To format a srting using the Date() object in Javascript.
  • To change a date format using Date.js where Date.ja is a built in Javascript library that allows formatting and parsing of date string.
  • We learnt to beautify a given date string format and compiled a Javascript program using Vanilla Javascript to format a Date string. Now, Having learnt the various methods and functions to change date format in javascript, it is now your turn to playaround with codes and implement in while building websites using Javascript.

Источник

JavaScript Date Format – How to Format a Date in JS

Joel Olawanle

Joel Olawanle

JavaScript Date Format – How to Format a Date in JS

JavaScript is one of the three fundamental web technologies you’ll use when developing websites or web applications.

When creating these web pages, you will, at some point, likely need to use dates for some reason – such as displaying when something was uploaded, stored, and so on.

In this article, you will learn how to format dates in JavaScript and see how you can do this with a popular JavaScript date library known as moment.js.

How to Get Dates in JavaScript

In JavaScript, you use either the new Date() or Date() constructor to get your dates (either current date or a specific date).

The new Date() constructor returns a new Date object, while the Date() constructor returns a string representation of the current date and time.

let stringDate = Date(); console.log(stringDate); // "Tue Aug 23 2022 14:47:12 GMT-0700 (Pacific Daylight Time)" let objectDate = new Date(); console.log(objectDate); // Tue Aug 23 2022 14:47:12 GMT-0700 (Pacific Daylight Time) 

These full format dates comprise the day, month, year, minute, hour, and other information you don’t need all the time.

Your primary concern is to see how you can format these date values to return dates in readable formats, which you can embed on your web page for everyone to understand.

How to Format Dates in JavaScript

Formatting dates depends on you and your needs. In some countries, the month comes before the day, then the year (06/22/2022). In others, the day comes before the month, then the year (22/06/2022), and lots more.

Regardless of the format, you want to break down the date object value and get the necessary information you want for your web page.

This is possible with the JavaScript date methods. There are many of these methods, but since you are only concerned with dates in this article, you will only need three of them:

  • getFullYear() – You will use this method to get the year as a four-digit number (yyyy). For example, 2022.
  • getMonth() – You will use this method to get the month as a number between 0-11, with each number representing the months from January to December. For example, 2 will be the index for March since it’s zero-based indexing (meaning it starts from 0 ).
  • getDate() – You will use this method to get the day as a number between 1-31 (this is not an index, but the exact day value, so it starts from 1 not 0).

Note: These methods can only be applied or will only work with the new Date() constructor, which returns a date object.

let objectDate = new Date(); let day = objectDate.getDate(); console.log(day); // 23 let month = objectDate.getMonth(); console.log(month + 1); // 8 let year = objectDate.getFullYear(); console.log(year); // 2022 

You will notice that 1 is added to the month value above. This is because the month is 0 indexed. The value starts from 0 . This means 7 will mean August instead of 8 .

At this point, you have been able to extract all date values from the date object. You can now organize them in whatever format you desire:

let format1 = month + "/" + day + "/" + year; console.log(format1); // 7/23/2022 let format2 = day + "/" + month + "/" + year; console.log(format2); // 23/7/2022 let format3 = month + "-" + day + "-" + year; console.log(format3); // 7-23-2022 let format4 = day + "-" + month + "-" + year; console.log(format4); // 23-7-2022 

In the above, you concatenated the values using the plus operator. You can also make use of template literals to concatenate:

let format1 = `$/$/$`; console.log(format1); // 7/23/2022 let format2 = `$/$/$`; console.log(format2); // 23/7/2022 let format3 = `$-$-$`; console.log(format3); // 7-23-2022 let format4 = `$-$-$`; console.log(format4); // 23-7-2022 

Now, you have seen the possible ways you may want to format your date.

Another scenario can be if you want the month and day value to be preceded by 0 if it’s a single numeric value (from 1-9). To do this, you would need to add a condition to handle this before formatting your dates:

if (day < 10) < day = '0' + day; >if (month < 10) < month = `0$`; > let format1 = `$/$/$`; console.log(format1); // 07/23/2022 

Interested in other ways you can format dates in JavaScript? Check out my article on «How to Format Dates in JavaScript with One Line of Code«.

How to Format Dates in JavaScript with Moment.js

Moment.js is a JavaScript date and time library that you can use to quickly format your dates without handling the logic with so many lines of code.

To use this library, you have to install the package in your project using any of your preferred options in the documentation.

For this guide, you are only concerned with how you can format dates with Moment.js:

let date = moment().format(); console.log(date); // 2022-08-23T16:50:22-07:00 

To format this date/time value, all you have to do is input your preferred format, and it will return the formatted date as seen below:

let dateFormat1 = moment().format('D-MM-YYYY'); console.log(dateFormat1); // 23-08-2022 let dateFormat2 = moment().format('D/MM/YYYY'); console.log(dateFormat2); // 23/08/2022 let dateFormat3 = moment().format('MM-D-YYYY'); console.log(dateFormat3); // 08-23-2022 let dateFormat4 = moment().format('MM/D/YYYY'); console.log(dateFormat4); // 08/23/2022 

Conclusion

This article has taught you how to format dates in JavaScript, either from scratch or with the moment.js library.

Be mindful when using a library for small projects, because libraries increase the size of your project. This is because these libraries are designed to handle many more operations. But to use any minimal operation, you still must install the entire library.

It is always recommended that you perform simple operations like this from scratch. That is, unless you are forced to use the library, or the library has been installed, or you are working on a large-scale project that requires some complex formatting.

Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.

Источник

Оцените статью