Format Datetime To String Javascript

4 min read Jun 19, 2024
Format Datetime To String Javascript

Formatting Datetime to String in JavaScript

JavaScript provides built-in methods for manipulating dates and times, but sometimes you need to convert a Date object into a formatted string for display or other purposes. Here's how to format datetime to string in JavaScript:

1. Using toString() and toLocaleString() Methods

The toString() and toLocaleString() methods provide basic formatting options:

const date = new Date();

console.log(date.toString()); // Output: "Tue Oct 24 2023 16:23:31 GMT+0700 (Western Indonesia Time)"
console.log(date.toLocaleString()); // Output: "10/24/2023, 4:23:31 PM"
  • toString(): Returns a string representation of the date in a standard format.
  • toLocaleString(): Returns a localized string representation of the date, depending on the user's locale settings.

2. Using Date.prototype.toLocaleDateString() and Date.prototype.toLocaleTimeString()

For more specific formatting, use toLocaleDateString() and toLocaleTimeString() with options:

const date = new Date();

// Formatting date
console.log(date.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })); // Output: "Tuesday, October 24, 2023"
console.log(date.toLocaleDateString('id-ID', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })); // Output: "Selasa, 24 Oktober 2023"

// Formatting time
console.log(date.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric' })); // Output: "4:23:31 PM"
console.log(date.toLocaleTimeString('id-ID', { hour: 'numeric', minute: 'numeric', second: 'numeric' })); // Output: "16:23:31"
  • toLocaleDateString(): Formats the date according to the specified locale and options.
  • toLocaleTimeString(): Formats the time according to the specified locale and options.

3. Using Date.prototype.toISOString()

This method returns a string in ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ):

const date = new Date();
console.log(date.toISOString()); // Output: "2023-10-24T09:23:31.000Z"

4. Using Custom Formatting with Intl.DateTimeFormat()

For maximum control over formatting, use the Intl.DateTimeFormat() constructor:

const date = new Date();
const formatter = new Intl.DateTimeFormat('en-US', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  timeZoneName: 'short'
});

console.log(formatter.format(date)); // Output: "October 24, 2023, 4:23:31 PM EST"

You can specify options like year, month, day, hour, minute, second, timeZoneName and more.

5. Using External Libraries

Libraries like Moment.js or Date-fns offer extensive date and time formatting capabilities. They provide more flexibility and a wider range of options compared to native JavaScript methods.

Remember to choose the method that best suits your needs and the level of customization required.