Phill Greggan
Phill Greggan

Reputation: 2394

How to remove time part from Date?

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?

Upvotes: 143

Views: 321472

Answers (13)

Azro
Azro

Reputation: 1

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

Upvotes: 0

Vijay Jagdale
Vijay Jagdale

Reputation: 2649

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

Upvotes: 150

Mugnum
Mugnum

Reputation: 1

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

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

Upvotes: -1

AlThePal78
AlThePal78

Reputation: 1112

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

public DateOnly Date {get; set}

Upvotes: -2

Jason
Jason

Reputation: 1072

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

Upvotes: 0

anchu n
anchu n

Reputation: 1

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"

Upvotes: 0

Adam Orłowski
Adam Orłowski

Reputation: 4464

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'

Upvotes: 3

Roberto
Roberto

Reputation: 424

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

Upvotes: 2

Monti
Monti

Reputation: 141

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

Upvotes: 13

Hayden
Hayden

Reputation: 11

previous answers are good. This is my method

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

Upvotes: 1

kreshnov
kreshnov

Reputation: 129

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

Upvotes: 12

Cerbrus
Cerbrus

Reputation: 72857

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

Upvotes: 64

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

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

Upvotes: 47

Related Questions