zaro

How to convert date in string format to date format in JavaScript?

Published in JavaScript Date Conversion 6 mins read

To convert a date from a string format to a Date object in JavaScript, you primarily use the built-in Date() constructor. This allows you to work with dates more effectively, perform calculations, and format them as needed.

Understanding JavaScript's Date Object

In JavaScript, the Date object is a fundamental part of working with dates and times. It stores a specific moment in time and provides various methods to manipulate and format that date. For comprehensive details on the Date object and its methods, refer to the MDN Web Docs.

Core Conversion Method: The Date() Constructor

The most direct way to convert a date string into a Date object is by passing the string directly to the Date() constructor.

Basic Usage

When you create a new Date object with a string argument, JavaScript attempts to parse that string into a date.

const dateString = "2023-10-27T10:00:00Z"; // ISO 8601 format
const dateObject = new Date(dateString);

console.log(dateObject); // Output: Fri Oct 27 2023 12:00:00 GMT+0200 (Central European Summer Time)
console.log(typeof dateObject); // Output: object

Handling Various String Formats

The Date() constructor is quite flexible but prefers certain standardized formats.

  • ISO Date Format (Recommended)

    • "YYYY-MM-DD" (e.g., "2023-10-27")
    • "YYYY-MM-DDTHH:mm:ss.sssZ" (e.g., "2023-10-27T10:30:00.000Z" for UTC time)
    • "YYYY-MM-DDTHH:mm:ss" (e.g., "2023-10-27T10:30:00" for local time)
    // ISO Date (UTC)
    const isoDateUTC = new Date("2023-10-27T14:30:00Z");
    console.log("ISO UTC:", isoDateUTC);
    
    // ISO Date (local time)
    const isoDateLocal = new Date("2023-10-27T14:30:00");
    console.log("ISO Local:", isoDateLocal);
  • Short Date Format

    • "MM/DD/YYYY" (e.g., "10/27/2023")
    • "YYYY/MM/DD" (e.g., "2023/10/27")
    // MM/DD/YYYY
    const shortDate1 = new Date("10/27/2023");
    console.log("Short Date 1:", shortDate1);
    
    // YYYY/MM/DD
    const shortDate2 = new Date("2023/10/27");
    console.log("Short Date 2:", shortDate2);
  • Long Date Format

    • "Month DD YYYY HH:mm:ss" (e.g., "Oct 27 2023 14:30:00")
    • "DD Month YYYY" (e.g., "27 Oct 2023")
    // Long Date
    const longDate = new Date("Oct 27 2023 14:30:00 GMT-0500 (CDT)");
    console.log("Long Date:", longDate);

Important Considerations:

  • Browser Inconsistencies: While standard formats are generally well-supported, parsing non-standard or ambiguous date strings can lead to inconsistent results across different browsers and JavaScript engines.
  • Time Zones: Be mindful of time zones. ISO 8601 strings ending with Z (Zulu time, or UTC) are parsed as UTC. Strings without time zone information are usually parsed as local time.

Custom Parsing for Non-Standard Formats

If your date string is in a non-standard format (e.g., "DD-MM-YYYY", "YYYY.MM.DD", or "DD/MM/YY" without leading zeros), the Date() constructor might not parse it correctly or consistently. In such cases, you'll need to manually parse the string.

Manual Parsing with split() and parseInt()

For formats like "DD-MM-YYYY", you can split the string and then create a Date object using the numeric constructor: new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds).

Remember that months are 0-indexed (January is 0, December is 11).

function parseDDMMYYYY(dateString) {
    const parts = dateString.split('-'); // Splits into ["DD", "MM", "YYYY"]
    const day = parseInt(parts[0], 10);
    const month = parseInt(parts[1], 10); // Month is 1-indexed in string
    const year = parseInt(parts[2], 10);

    // Create Date object: month is 0-indexed in Date constructor
    return new Date(year, month - 1, day);
}

const customDateString = "27-10-2023";
const customDateObject = parseDDMMYYYY(customDateString);
console.log("Custom Parsed Date:", customDateObject);

// Example for DD/MM/YY
function parseDDMMYY(dateString) {
    const parts = dateString.split('/');
    const day = parseInt(parts[0], 10);
    const month = parseInt(parts[1], 10);
    let year = parseInt(parts[2], 10);

    // Handle two-digit year (e.g., '23' becomes '2023')
    if (year < 100) {
        year += 2000; // Adjust as per your specific century logic
    }
    return new Date(year, month - 1, day);
}

const twoDigitYearString = "27/10/23";
const twoDigitYearObject = parseDDMMYY(twoDigitYearString);
console.log("Two-Digit Year Parsed:", twoDigitYearObject);

Extracting Date Components from a Date Object

Once you have a Date object, you can easily retrieve individual components (day, month, year, etc.) and reformat them into any string format you desire. This is useful for displaying dates in specific localized formats.

Useful Methods for Formatting

JavaScript's Date object provides several getter methods:

  • getDate(): Returns the day of the month (1-31).
  • getMonth(): Returns the month (0-11), where 0 is January and 11 is December.
  • getFullYear(): Returns the full year (e.g., 2023).
  • getHours(): Returns the hour (0-23).
  • getMinutes(): Returns the minutes (0-59).
  • getSeconds(): Returns the seconds (0-59).
  • getMilliseconds(): Returns the milliseconds (0-999).
  • getDay(): Returns the day of the week (0 for Sunday, 6 for Saturday).

Example: Formatting into "DD-MM-YYYY"

const myDateObject = new Date(); // Or your previously converted date, e.g., new Date("2023-10-27")

const day = String(myDateObject.getDate()).padStart(2, '0');
// getMonth() returns 0-11, so add 1 for 1-12, then pad
const month = String(myDateObject.getMonth() + 1).padStart(2, '0');
const year = myDateObject.getFullYear();

const formattedDate = `${day}-${month}-${year}`;
console.log("Formatted Date (DD-MM-YYYY):", formattedDate); // Example: "27-10-2023"

// Example: Formatting into "YYYY/MM/DD HH:MM"
const hours = String(myDateObject.getHours()).padStart(2, '0');
const minutes = String(myDateObject.getMinutes()).padStart(2, '0');

const formattedDateTime = `${year}/${month}/${day} ${hours}:${minutes}`;
console.log("Formatted Date/Time (YYYY/MM/DD HH:MM):", formattedDateTime);

When to Use a Date Library

For more complex date manipulation, internationalization, or robust timezone handling, dedicated JavaScript date libraries are highly recommended. Popular options include:

  • date-fns: A modern JavaScript date utility library. It's modular, so you only import what you need.
  • Luxon: A powerful, immutable, and easy-to-use wrapper for the JavaScript Date object.

These libraries provide more consistent parsing behavior, simplified formatting, and advanced features that go beyond the native Date object's capabilities.

Comparison of Methods

Here's a quick overview of the different approaches to converting date strings:

Method Pros Cons Best For
new Date(string) Simple, native, no external dependencies Inconsistent parsing for non-standard formats, timezone ambiguity Standard ISO or well-defined English formats
Manual Parsing Full control over parsing logic, handles any format More verbose, error-prone if not carefully implemented, no built-in timezone handling Specific, non-standard date formats
Date Libraries Robust, consistent, rich API, timezone support, internationalization Adds external dependency, increases bundle size Complex date logic, large-scale applications, global date handling

By understanding these methods, you can choose the most appropriate way to convert and manage dates in your JavaScript applications, ensuring accuracy and consistency.