Home >Web Front-end >JS Tutorial >How to Convert Strings to Datetime Objects in JavaScript with Custom Format Specifications?
Converting Strings to Datetimes with Format Specifications in JavaScript
Question:
How can we convert a string to a datetime object in JavaScript while specifying a format string?
Implementation:
For formats compatible with Date.parse(), the conversion can be done using the new Date(dateString) method. However, for incompatible formats, manual parsing is necessary.
Manual Parsing:
Date Object Creation:
Use explicit values for these components to create a new Date object:
const date = new Date(year, month - 1, date, hour, minute, second);
Example:
To convert "23.11.2009 12:34:56" with the format "dd.MM.yyyy HH:mm:ss":
const dateString = "23.11.2009 12:34:56"; const format = "dd.MM.yyyy HH:mm:ss"; // Split the string into components const [date, time] = dateString.split(" "); const [day, month, year] = date.split("."); const [hour, minute, second] = time.split(":"); // Create a new date object const dateObject = new Date(year, month - 1, day, hour, minute, second);
The above is the detailed content of How to Convert Strings to Datetime Objects in JavaScript with Custom Format Specifications?. For more information, please follow other related articles on the PHP Chinese website!