147

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?

8
  • 3
    Split it on ' ' and get the first part? Commented Jan 11, 2016 at 13:35
  • 1
    slice(0, 10) Commented Jan 11, 2016 at 13:36
  • @RyanO'Hara i also thought of that but assume i need to assign it to a datepicker is that the proper way of doing it? Commented Jan 11, 2016 at 13:37
  • 5
    already answered by stackoverflow.com/questions/15130735/… Commented Jan 11, 2016 at 13:37
  • 7
    The original question is about a string which somehow represents a string... For people interesting in truncating a Javascript Date object (as in the question title): var d = new Date(); var startOfDay = new Date(d.getFullYear(), d.getMonth(), d.getDate()); Moreover, the duplicate is definitely not the same question as it is about Moment.js. Commented Sep 20, 2017 at 8:56

13 Answers 13

152

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

Sign up to request clarification or add additional context in comments.

Comments

68

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()); 

5 Comments

There’s only one date format that JavaScript implementations are required to be able to parse, and this isn’t it. es5.github.io/#x15.9.1.15
@RyanO'Hara: Name one browser that can't (properly) parse a date string in this format.
You tried to tell me my answer was somehow incorrect, because the date string isn't part of a standard. Yet all browsers support it. "Easier and faster" isn't necessarily "Better". Teaching a user to parse dates properly helps him when he needs to work with dates more, in the future. Just splitting the string only helps him in this specific case.
Teaching a user to parse dates in a way that works by happenstance is not something I agree with, sorry. It is far better to parse parts of a date from an exact format and then construct it when you need one.
By happenstance? It's a commonly used format that all browsers support. That's not a coincidence.
47

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); 

7 Comments

If you're going to work with dates, don't suggest string manipulation like that.
@Cerbrus so the proper way would be the regenerate a date using it
Sure, it may work, often enough, just getting the date part isn't the only thing you need to do. Parsing it into a Date object helps when you eventually need to use the date for other purposes.
@iambriansreed: Problems with timezones are exactly what you avoid using string manipulation. And, as I commented on that answer, it’s not guaranteed to work in a standards-compliant JavaScript environment (even worse if the environment decides to parse it as the wrong one of MM/DD/YYYY and DD/MM/YYYY based on the user’s locale – can you tell me offhand whether any browsers have done that?). Use moment.js if you need serious date work.
. JavaScript has a Date object for a reason. If your string represents a Date, convert it to a Date object, and then operate on it. SEE @Cerbrus ANSWER BELOW
|
13

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()

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
This is the right answer. The author's date string is formatted according to their own locale using the expression new Date(1955, 11, 12).toLocaleString(). toLocaleTimeString and toLocaleDateString can be used to format the time or date, respectively.
12

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); 

Comments

4

A lot of working answers but I'd suggest using Intl.DateTimeFormat

const dateString = '12/12/1955 12:00:00 AM'; const date = new Date(dateString); new Intl.DateTimeFormat('en-GB', { year: 'numeric', month: 'numeric', day: 'numeric', }).format(date); 

Output: '12/12/1955'

Comments

3

Sorry, I like oneliners. Given that original date d can be replaced:

d.setHours(-d.getTimezoneOffset() / 60, 0, 0, 0)) 

Or, maybe the sorter and less destructive:

new Date(d.toJSON().substr(0, 10)) 

2 Comments

This is what I needed: -d.getTimezoneOffset() / 60. I was trying to understand why setting hours to 0 moved me back to 11pm the previous day. It seems this is the solution. Not easily intuited though!
Actually, I noticed I was printing the ISO string and that's what was showing 23:00. Prinitng out the date in BST showed that it was in fact 00:00 as expected so I believe adzusting by the timeozne offset might actually be incorrect and in fact d.setHours(0, 0, 0, 0)) gives the correct date.
1

previous answers are good. This is my method

var todaysDate = new Date; todaysDate = todaysDate.toDateString(); console.log(todaysDate);

Comments

0

In JavaScript, you can use the .slice() method to remove the time from a string:

let dateTime = "2023-01-16T08:48:31.702+00:00"; let dateOnly = dateTime.slice(0, 10); console.log(dateOnly); //Output: "2023-01-16" 

Comments

0

Sorry for the long-winded answer here, but it might help somebody in the same boat. My use case:

  1. I have a date stored in a database. The database server is not in UTC, but we want to use date out of a field, disregarding the time, and disregarding any timezone conversion. I want to get a date of "Dec 31, 2022" from a database with '2022-12-31 01:30:00' in the current time zone..

  2. I can count on the database to return datetime/timestamp fields beginning with 'YYYY-MM-DD' followed by whatever time is stored (if applicable)

  3. I want to compare that date against "today" (again, in the current time zone).

I was happily using Moment.js, but I guess that's not en-vogue now. Rather than get some other library that will also go away at some point because it's not loved anymore, I decided to try and solve it myself. I don't care about time zone conversion, I just want dates to match.

The following is a bit verbose, but easily can be whittled down to something more minimalist, or you could extend the Date prototype, etc.

I've tested this with my timezone set to Hong Kong, New York and UTC. It seems to work for them all.

One other thing, this is kind of an academic exercise since it's pretty easy to just compare the YYYY-MM-DD strings and not deal with all of this nonsense in the first place. :)

But, for those morbidly curious, here is the class:

export default class DateUtilty { private static readonly dateFormat = /^\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])/; /** * Parse text, looking for a date portion only in YYYY-MM-DD format, * and adjust it to be the start-of-day in the local time zone (whatever it is). * This will allow us to more easily compare the date portion of stored values * @param text * @returns parsed Date or undefined */ public static ParseDateOnly(text: string): Date | undefined { const results = this.dateFormat.exec(text); if (results && results.length > 0) { const dt = new Date(results[0]); return new Date(dt.getTime() + dt.getTimezoneOffset() * 60000); } else { return undefined; } } /** * Format date time * @param date * @returns date in YYYY-MM-DD format */ public static DateToYMD(date: Date): string { return `${date.getFullYear()}-${date.toLocaleString('default', { month: '2-digit' })}-${date.toLocaleString('default', { day: '2-digit' })}`; } } 

The tests...

describe('DateUtility', () => { describe('ParseDateOnly', () => { it('returns same value for same date and date with time', () => { const dt1 = DateUtility.ParseDateOnly('2023-02-01 03:08:51.0'); const dt2 = DateUtility.ParseDateOnly('2023-02-01'); expect(dt1).toEqual(dt2); }); it('returns same value for today and today with time', () => { const today = new Date; // Force to the date for today to start of day const todayDate = new Date(today.setHours(0, 0, 0, 0)); // Get today in YYYY-MM-DD format, which we know is parsable by Date const todayText = DateUtility.DateToYMD(today); // Parse today's date, and adjust to start of day const dt1 = DateUtility.ParseDateOnly(todayText); // Should be equal expect(todayDate).toEqual(dt1); }); }); describe('DateToYMD', () => { it('returns in YYYY-MM-DD format', () => { expect(DateUtility.DateToYMD(new Date('2023-01-01 12:30:00'))).toEqual('2023-01-01'); }); }); }); 

Comments

0

const date = new Date(); // localeString const localeString = date.toLocaleString(); console.log(localeString) //Output: 24/09/2024, 14:49:43 // localeDateString const localeDateString = date.toLocaleDateString(); console.log(localeDateString) //Output: 24/09/2024

Comments

-2

Even though I said this month I think you can use this for your models

public DateOnly Date {get; set} 

1 Comment

That does nothing for the OP. A public property declaration is not the answer. The OP asked how to display a given date and time without the time part.
-2

In case your project is using ExtJS framework, you can also remove the time this way:

Ext.Date.clearTime(new Date()); 

1 Comment

is this a generic solution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.