128

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?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Phill Greggan
  • 2,234
  • 3
  • 20
  • 33
  • 3
    Split it on `' '` and get the first part? – Ry- Jan 11 '16 at 13:35
  • 1
    [`slice(0, 10)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) – hindmost Jan 11 '16 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? – Phill Greggan Jan 11 '16 at 13:37
  • 5
    already answered by ***http://stackoverflow.com/questions/15130735/how-can-i-remove-time-from-my-date-with-moment-js*** – Ruwini opatha Jan 11 '16 at 13:37
  • @PhillGreggan What is the format required to pass the date to datepicker – Tushar Jan 11 '16 at 13:43
  • @Tushar it worked by the answers given by Ryan O'Hara and Azim. the format is US datetime – Phill Greggan Jan 11 '16 at 13:44
  • 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. – Myobis Sep 20 '17 at 08:56
  • For more accurate details for removing the time part from javascript date check https://stackoverflow.com/questions/2698725/comparing-date-part-only-without-comparing-time-in-javascript – Serene Abraham Mathew Jan 27 '21 at 06:56

11 Answers11

129

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

Vijay Jagdale
  • 2,321
  • 2
  • 18
  • 16
59

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());
Maxim
  • 13,029
  • 6
  • 30
  • 45
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • 7
    There’s only one date format that JavaScript implementations are required to be able to parse, and this isn’t it. https://es5.github.io/#x15.9.1.15 – Ry- Jan 11 '16 at 13:47
  • 7
    @RyanO'Hara: Name _one_ browser that can't (properly) parse a date string in this format. – Cerbrus Jan 11 '16 at 13:48
  • 7
    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. – Cerbrus Jan 11 '16 at 13:53
  • 3
    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. – Ry- Jan 11 '16 at 14:10
  • 8
    By happenstance? It's a commonly used format that _all_ browsers support. That's not a coincidence. – Cerbrus Jan 11 '16 at 14:15
48

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);
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
  • 99
    If you're going to work with dates, don't suggest string manipulation like that. – Cerbrus Jan 11 '16 at 13:44
  • @Cerbrus so the proper way would be the regenerate a date using it – Phill Greggan Jan 11 '16 at 13:45
  • 2
    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. – Cerbrus Jan 11 '16 at 13:47
  • @Ryan This is not recommended as date strings are often returned with a timezone (utc usually) which is not the same as the local machine running the js. There is a chance the date you string.split off may not be the same date once time and timezone are considered. This is why I downvoted this answer and upvoted this. https://stackoverflow.com/a/34723015/144665 – iambriansreed Sep 19 '17 at 19:35
  • 4
    @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. – Ry- Sep 19 '17 at 23:59
  • Indeed, split on space. Or if it is an ISO Date, split on 'T' `new Date().toISOString().split('T')[0]` – Mike Irving Feb 01 '19 at 14:20
  • 3
    . 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 – T Blank Apr 25 '19 at 20:15
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);
kreshnov
  • 129
  • 1
  • 3
6

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

sggranil
  • 71
  • 1
  • 5
  • 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](/help/how-to-answer). – Community Jan 19 '22 at 15:49
3

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'

Adam Orłowski
  • 4,268
  • 24
  • 33
1

previous answers are good. This is my method

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

Hayden
  • 11
  • 1
0

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))
Roberto
  • 374
  • 6
  • 9
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"
anchu n
  • 1
  • 1
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');
        });
    });
});
Jason
  • 941
  • 1
  • 10
  • 19
-1

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

public DateOnly Date {get; set}
AlThePal78
  • 793
  • 2
  • 14
  • 25
  • 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. – Paul-Sebastian Manole Jul 04 '23 at 10:52