Javascript new date format
In JavaScript, the Date
object has several methods to format dates in different ways. Here are some common ones:
toString()
: Returns a string representation of the date in the format "Fri Jan 12 2023 14:30:00 GMT-0500 (Eastern Standard Time)".toDateString()
: Returns a string representation of the date in the format "Fri Jan 12 2023".toTimeString()
: Returns a string representation of the time in the format "14:30:00 GMT-0500".toLocaleString()
: Returns a string representation of the date in the format "January 12, 2023 2:30:00 PM Eastern Standard Time".toLocaleDateString()
: Returns a string representation of the date in the format "January 12, 2023".toLocaleTimeString()
: Returns a string representation of the time in the format "2:30:00 PM".
You can also use the toISOString()
method to get a string representation of the date in the format "2023-01-12T14:30:00.000Z".
If you want to format a date in a specific way, you can use the toLocaleFormat()
method, which takes a format string as an argument. For example:
const date = new Date();
const formattedDate = date.toLocaleFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
console.log(formattedDate); // Output: "2023-01-12T14:30:00.000-0500"
Alternatively, you can use a library like Moment.js or Date-fns to format dates in a more flexible and customizable way.
Here are some examples of formatting dates using Moment.js:
const moment = require("moment");
const date = new Date();
const formattedDate = moment(date).format("YYYY-MM-DD HH:mm:ss");
console.log(formattedDate); // Output: "2023-01-12 14:30:00"
And here are some examples of formatting dates using Date-fns:
const { format } = require("date-fns");
const date = new Date();
const formattedDate = format(date, "yyyy-MM-dd'T'HH:mm:ss.SSSZ");
console.log(formattedDate); // Output: "2023-01-12T14:30:00.000Z"
Note that the format strings used in these examples are just a few examples of the many possible formats you can use. You can customize the format strings to suit your specific needs.