I have a date '12/12/1955 12:00:00 AM'
stored in a hidden column. I want to display the date without the time.
How do I do this?
We can remove the time portion from a date with the startOf method. We pass in a date with the hour and minutes set into the moment function. Then we call startOf with the 'day' argument to get return a moment object with the time set to midnight of the same date.
To remove the T and Z characters from an ISO date in JavaScript, we first need to have the date in ISO format. If you don't have it already, you can convert it to ISO using the toISOString function on a Date object. This will get rid of both T and Z, resulting in "2022-06-22 07:54:52.657".
To subtract hours from a date:Use the getHours() method to get the hours of the specific date. Use the setHours() method to set the hours for the date. The setHours method takes the hours as a parameter and sets the value for the date.
This is probably the easiest way:
new Date(<your-date-object>.toDateString());
Example: To get the Current Date without time component:
new Date(new Date().toDateString());
gives: Thu Jul 11 2019 00:00:00 GMT-0400 (Eastern Daylight Time)
Note this works universally, because toDateString()
produces date string with your browser's localization (without the time component), and the new Date()
uses the same localization to parse that date string.
You can extend the Date object as below, so and then use the dateOnly property:
Date.prototype.getDateWithoutTime = function () {
return new Date(this.toDateString());
}
Now <any-date-object>.getDateWithoutTime();
will output Date only
Parse that string into a Date
object:
var myDate = new Date('10/11/1955 10:40:50 AM');
Then use the usual methods to get the date's day of month (getDate
) / month (getMonth
) / year (getFullYear
).
var noTime = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate());
Split it by space
and take first part like below. Hope this will help you.
var d = '12/12/1955 12:00:00 AM';
d = d.split(' ')[0];
console.log(d);
The previous answers are fine, just adding my preferred way of handling this:
var timePortion = myDate.getTime() % (3600 * 1000 * 24);
var dateOnly = new Date(myDate - timePortion);
If you start with a string, you first need to parse it like so:
var myDate = new Date(dateString);
And if you come across timezone related problems as I have, this should fix it:
var timePortion = (myDate.getTime() - myDate.getTimezoneOffset() * 60 * 1000) % (3600 * 1000 * 24);
This is perhaps the most effective solution.
var date = new Date().toLocaleDateString();
Example code below:
var dateToday = '2/19/2022, 12:00:00 AM';
var date = new Date(dateToday).toLocaleDateString();
console.log(date); // Output: 2/19/2022
Documentation: MDN Web Docs - Date.prototype.toLocaleDateString()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With