How to Convert String to Date in Javascript in dd-mmm-yyyy Format

by | JavaScript

Stuck on converting a string to a date in Javascript, let’s sort that out.

You can convert strings to dates in the “DD-MMM-YYYY” format using the Date() constructor or the Date.parse() method. You can also convert strings to a date object using third-party libraries like the dayjs or the date-fns libraries.

This article will teach you how to achieve this conversion, ensuring that your date strings are consistently interpreted as intended.

So, let’s explore how you can deal with date strings in the “DD-MMM-YYYY” format effectively in your code!

How to Convert dd-MMMM-YYYY String to Date in Javascript

How to convert string to date in javascript in dd-mmm-yyyy format

When building Javascript applications, you might often encounter crucial variables like dates and times in string formats. You cannot work with them properly in this format, and you need to convert them.

Here are the 4 best ways to convert.

1. Using the Javascript Date Object

JavaScript provides a built-in Date class that you can use to work with date and time. You can create a new Date object by using the new Date() constructor. By default, this will provide you with the current date and time.

You can also convert strings in the dd-mmm-yyyy format to date objects by placing them inside the Date() constructor. Let’s look at an example:

let currentDate = new Date();
console.log(currentDate);
let christmasDay = new Date("25-Dec-2022 UTC")
console.log(christmasDay) 

Output:

2023-11-17T17:33:47.118Z
2022-12-25T00:00:00.000Z

The code above returns two date objects. One with the current date and time and another with the date string we placed into the constructor.

You can also use this same method when the date is in the format of dd/mmm/yyyy. It will convert it to a date object just fine.

let christmasDay = new Date("25/Dec/2022 UTC")
console.log(christmasDay) 

Output:

2022-12-25T00:00:00.000Z

However, you cannot use it to convert a date that’s in the dd/mm/yyyy format. It will always return an error that states that the string is an Invalid Date. Here’s an example:

let christmasDay = new Date("25/12/2022 UTC")
console.log(christmasDay) 

Output:

invalid Date

Note: Adding the UTC suffix after the date is necessary to avoid timezone conflicts. You can also specify a custom timezone like GMT or EST.

2. Using the Parse Method

The Date.parse() function is a static method in JavaScript that is useful for converting a string into a date object by interpreting the string’s content. It takes in the date string and returns a timestamp which represents the amount of milliseconds that have elapsed since the Unix epoch(01 Jan. 1970).

For instance:

let dateString = "04-Oct-2023";
let timestamp = Date.parse(dateString);
console.log(timestamp)

Output:

1696374000000

However, this method has one caveat. It does not directly convert the string into a date object. You can use it in combination with the Date() constructor to convert the timestamp into a date object.

let dateString = "04-Oct-2023 UTC";
let timestamp = Date.parse(dateString);
let dateObject = new Date(timestamp);

console.log(dateObject)

Output:

full date object

Now, it returns a full date object.

3. Using a Split Function

When we have a date string in a format like dd-mm-yyyy or dd/mm/yyyy, we can’t convert it to a date object using any of the methods highlighted above. Using any of them will result in Nan, an Invalid Date result, or an incorrect date object.

To convert these date formats into a date object, we have to write a function to split them up into day, month, and year. After splitting them up, we can pass them into a Date constructor to create the date object. Let’s look at an example:

function dateSplit(dateString){
    const dateParts = dateString.split("-");
    return new Date(Date.UTC(dateParts[2], dateParts[1]-1, dateParts[0]))

}

console.log(dateSplit("25-12-2023"))

Output:

2023-12-25T00:00:00.000Z

For date strings in the format dd/mm/yyyy we can easily change the parameter in the split function to /.

Note: The months in the Javascript Date object are zero-based. For example, January is 0, May is 4, etc. That’s why we have the dateParts[1]-1 variable in the constructor.

4. Using the Day.js Library

Day.js is a lightweight, minimalist library that you can use to easily parse date strings and convert them into date objects. It also has several other useful features that make it a great alternative to the Date library.

To install it, simply run the following command in your terminal.

npm install dayjs

Once you have it installed, here’s how you can convert strings in the format dd-mmm-yyyy to date objects.

const dayjs = require("dayjs")

const dateObj = dayjs("23-Oct-2020", "dd-mmm-yyyy")
console.log(dateObj)

Output:

day.js library

All you have to do is pass in the date string and also pass in the format that the date string variable is in. This method is very flexible and you can use it to parse a wide range of date strings into date objects. For example, let’s say you want to parse a string in the dd-mm-yyyy format into a date object:

const dayjs = require("dayjs")

const dateObj = dayjs("23/11/2020", "dd-mm-yyyy")

How to Display a Date Object in the dd-mmm-yyyy Format

Now that we’ve discussed how to parse date strings in this format, let’s look at how we can display date objects in this format.

As we’ve seen in the examples above, when the date objects are printed out they usually appear in the format yyyy-mm-dd.

To display them in the dd-mmm-yyyy format, here are some methods you can use:

Using the Date Object’s Get Methods

The Date library contains several get() methods that can be used to retrieve date components when converting a date object into a string in a particular format. To get the desired format of dd-mmm-yyyy, you’ll need to extract the relevant information and concatenate it.

Here’s an example:

function toString(dateObject){
    let day = dateObject.getDate();
    let monthIndex = dateObject.getMonth();
    let year = dateObject.getFullYear();
    let monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",         "Sep", "Oct", "Nov", "Dec"];
    let month = monthNames[monthIndex];
     return `${day}-${month}-${year}`;
    }
const valDay = new Date("2023/02/14 UTC")
console.log(toString(valDay))

Output:

Display Date String

The toString function takes in a date object, retrieves the day, month, and year from it, and then concatenates them together as a string. This will give you a string representation of the date in the desired format.

The ToLocaleString Function

Another useful function to format dates is toLocaleString(). This function takes two optional parameters: locales and options. The locales parameter allows you to specify the language and region for formatting, while the options parameter lets you customize the display.

Here’s an example of using toLocaleString() to convert a Date object into the desired format using the UK standard:

let dateObject = new Date("2023/07/04 UTC")
let options = { day: '2-digit', month: 'short', year: 'numeric' };
let formattedDate = dateObject.toLocaleString('en-gb', options);

Output:

04 Jul 2023

In the options object, we specify the day as 2 digits, the month as short, and the year as numeric. When we pass it into the toLocaleString methods specifying the Great Britain(en-gb) standard, it returns a date string in the format of dd-mmm-yyyy, such as “04 Jul 2023”.

Using the dayjs Library

We can also use the dayjs library we described above to display date objects in the required format Here’s an example:

const dayjs = require("dayjs");

const date = dayjs("2023-05-30 UTC");
const formatted = date.format("DD-MMM-YYYY");
console.log(formatted);

Output:

The dayjs library formats it

We pass in the date to the module in the ISO format yyyy-mm-dd. The dayjs library formats it and returns it in the dd-mmm-yyyy format.

Final Thoughts

Mastering string-to-date conversion in JavaScript for different formats is a valuable skill to have when building web applications.

This article has walked you through the steps to achieve just that, focusing on the DD-MMM-YYY format.

As you apply these principles in your code, you’ll find yourself not just manipulating dates but crafting a more precise and user-friendly experience. Good Luck!

If you want to learn how to boost your productivity with AI, be sure to check out our video on Unleashing The Power Of OpenAI’s Code Interpreter For Data Analysis.

Frequently Asked Questions

What date format does Javascript accept?

Javascript accepts many date formats, but the most recommended date format to use is the ISO8601 date time format. It follows the YYYY-MM-DD format.

Other acceptable formats include:

  • DD-MMM-YYYY

  • DD-MMMM-YYYY

  • YYYY-MM-DDD

How do I convert a timestamp to a formatted date string in JavaScript?

You can convert a timestamp to a formatted date string in JavaScript by first creating a Date object with it. Then, you can use the toLocaleString method we went over in the article to format the date object.

Let’s look at an example:

const timestamp = 1633335600000; // example timestamp
const dateObj = new Date(timestamp);
let options = { day: '2-digit', month: 'short', year: 'numeric' };
let formattedDate = dateObj.toLocaleString('en-gb', options);
console.log(formattedDate)

Output:

04 Oct 2021

What are some efficient ways to extract and format a date from a string in JavaScript?

To extract and parse a date from a string in JavaScript, you can use regular expressions in conjunction with the Date constructor. Let’s look at an example:

const day = "The final paper is due on 25/Apr/2023. You should have it by then."
const pattern = /d{1,2}/w{3}/d{4}/
let matches = day.match(pattern)
for (match of matches){
    console.log(new Date(match+ " UTC"))
}

Output:

2023-04-25T00:00:00.000Z

This code snippet extracts the date information from the string, creates a Date object, and displays it in the console.

author avatar
Sam McKay, CFA
Sam is Enterprise DNA's CEO & Founder. He helps individuals and organizations develop data driven cultures and create enterprise value by delivering business intelligence training and education.

Related Posts