When building applications with JavaScript, there might be scenarios where you want to remove the time portion from a date string, such as:
- Displaying dates: When displaying dates in a UI, you may only want to show the date part and not the time.
- Storing dates: When storing the prices of stocks, you usually don’t need the time part.
This concise, example-based article will show you a couple of different ways to do so.
Table Of Contents
Using string manipulation
Example:
// Input date string in ISO format
const dateString = '2023-03-07T14:30:00.000Z';
// Truncate time portion
const truncatedDate = dateString.split('T')[0];
console.log(truncatedDate);
Output:
2023-03-07
Using Date object
Example:
// Input date string in YYYY-MM-DD HH:MM:SS format
const dateString = '2023-12-30 12:00:00';
// Convert to Date object
const dateObj = new Date(dateString);
// Get only the date part
const truncatedDate =
dateObj.getFullYear() +
'-' +
(dateObj.getMonth() + 1) +
'-' +
dateObj.getDate();
console.log(truncatedDate);
Output:
2023-12-30
Using Regular Expressions
You can also use a regular expression to match the time portion of the given date string and replace it with an empty string.
Example:
// Input date string
const dateString = '2024-03-07T14:30:00.000Z';
// Truncate time portion using regular expressions
const truncatedDate = dateString.replace(/T.+/, '');
console.log(truncatedDate);
Output:
2024-03-07
That’s it. If you have any questions, please comment. Happy coding & have a nice day!