Try this:

function dateToEpoch(thedate) {
    var time = thedate.getTime();
    return time - (time % 86400000);
}

or this:

function dateToEpoch2(thedate) {
   return thedate.setHours(0,0,0,0);
}

Example : http://jsfiddle.net/chns490n/1/

Reference: (Number) Date.prototype.setHours(hour, min, sec, millisec)

Answer from trrrrrrm on Stack Overflow
๐ŸŒ
Medium
medium.com โ€บ @sampathsl โ€บ how-to-convert-javascript-date-without-time-stamp-6dcc2aeb2190
How to convert JavaScript Date without time stamp | by Sampath Thennakoon | Medium
January 10, 2017 - When you try JavaScript new Date() in browser console, you can see date with time stamp. ... To remove time stamp what I did was use new Date with year , month and day parameters. new Date(new Date().getFullYear(),new Date().getMonth() , new ...
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ javascript-get-date-without-time
How to get a Date without the Time in JavaScript | bobbyhadz
Use the `setHours()` method to get a date without the time, e.g. `new Date().setHours(0, 0, 0, 0)`.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Date โ€บ Date
Date() constructor - JavaScript | MDN
If called with an invalid date string, or if the date to be constructed will have a timestamp less than -8,640,000,000,000,000 or greater than 8,640,000,000,000,000 milliseconds, it returns an invalid date (a Date object whose toString() method returns "Invalid Date" and valueOf() method returns ...
๐ŸŒ
SourceFreeze
sourcefreeze.com โ€บ home โ€บ how to get a date without the time in javascript
How to get a Date without the Time in JavaScript - Source Freeze
December 20, 2023 - // Get the current date const ...ISOString(); // Extract only the date part const dateWithoutTime = dateISOString.split('T')[0]; console.log('Date without time:', dateWithoutTime);...
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_date_methods.asp
JavaScript Get Date Methods
The time in a date object is NOT the same as current time. The getFullYear() method returns the year of a date as a four digit number: const d = new Date("2021-03-25"); d.getFullYear(); Try it Yourself ยป ยท const d = new Date(); d.getFullYear(); Try it Yourself ยป ยท Old JavaScript code might use the non-standard method getYear().
๐ŸŒ
Talkerscode
talkerscode.com โ€บ howto โ€บ getting-date-without-time-in-javascript.php
Getting Date Without Time In JavaScript
To get the date without the time, we will utilize the JavaScript Date object and its various methods. The Date object represents a specific moment in time and provides several useful methods for manipulating and extracting date components. We will leverage the getFullYear(), getMonth(), and getDate() methods to obtain the year, month, and day respectively, and then construct a new date string without the time component...
Top answer
1 of 16
958

I'm still learning JavaScript, and the only way that I've found which works for me to compare two dates without the time is to use the setHours method of the Date object and set the hours, minutes, seconds and milliseconds to zero. Then compare the two dates.

For example,

date1 = new Date()
date2 = new Date(2011,8,20)

date2 will be set with hours, minutes, seconds and milliseconds to zero, but date1 will have them set to the time that date1 was created. To get rid of the hours, minutes, seconds and milliseconds on date1 do the following:

date1.setHours(0,0,0,0)

Now you can compare the two dates as DATES only without worrying about time elements.

2 of 16
259

BEWARE THE TIMEZONE

Using the date object to represent just-a-date straight away gets you into a huge excess precision problem. You need to manage time and timezone to keep them out, and they can sneak back in at any step. The accepted answer to this question falls into the trap.

A javascript date has no notion of timezone. It's a moment in time (ticks since the epoch) with handy (static) functions for translating to and from strings, using by default the "local" timezone of the device, or, if specified, UTC or another timezone. To represent just-a-date with a date object, you want your dates to represent UTC midnight at the start of the date in question. This is a common and necessary convention that lets you work with dates regardless of the season or timezone of their creation. So you need to be very vigilant to manage the notion of timezone, both when you create your midnight UTC Date object, and when you serialize it.

Lots of folks are confused by the default behaviour of the console. If you spray a date to the console, the output you see will include your timezone. This is just because the console calls toString() on your date, and toString() gives you a local represenation. The underlying date has no timezone! (So long as the time matches the timezone offset, you still have a midnight UTC date object)

Deserializing (or creating midnight UTC Date objects)

This is the rounding step, with the trick that there are two "right" answers. Most of the time, you will want your date to reflect the local timezone of the user. What's the date here where I am.. Users in NZ and US can click at the same time and usually get different dates. In that case, do this...

// create a date (utc midnight) reflecting the value of myDate and the environment's timezone offset.
new Date(Date.UTC(myDate.getFullYear(),myDate.getMonth(), myDate.getDate()));

Sometimes, international comparability trumps local accuracy. In that case, do this...

// the date in London of a moment in time. Device timezone is ignored.
new Date(Date.UTC(myDate.getUTCFullYear(), myDate.getUTCMonth(), myDate.getUTCDate()));

Deserialize a date

Often dates on the wire will be in the format YYYY-MM-DD. To deserialize them, do this...

var midnightUTCDate = new Date( dateString + 'T00:00:00Z');

Serializing

Having taken care to manage timezone when you create, you now need to be sure to keep timezone out when you convert back to a string representation. So you can safely use...

  • toISOString()
  • getUTCxxx()
  • getTime() //returns a number with no time or timezone.
  • .toLocaleDateString("fr",{timeZone:"UTC"}) // whatever locale you want, but ALWAYS UTC.

And totally avoid everything else, especially...

  • getYear(),getMonth(),getDate()

So to answer your question, 7 years too late...

<input type="date" onchange="isInPast(event)">
<script>
var isInPast = function(event){
  var userEntered = new Date(event.target.valueAsNumber); // valueAsNumber has no time or timezone!
  var now = new Date();
  var today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ));
  if(userEntered.getTime() < today.getTime())
    alert("date is past");
  else if(userEntered.getTime() == today.getTime())
    alert("date is today");
  else
    alert("date is future");

}
</script>

See it running...

Update 2022... free stuff with tests ...

The code below is now an npm package, Epoq. The code is on github. You're welcome :-)

Update 2019... free stuff...

Given the popularity of this answer, I've put it all in code. The following function returns a wrapped date object, and only exposes those functions that are safe to use with just-a-date.

Call it with a Date object and it will resolve to JustADate reflecting the timezone of the user. Call it with a string: if the string is an ISO 8601 with timezone specified, we'll just round off the time part. If timezone is not specified, we'll convert it to a date reflecting the local timezone, just as for date objects.

function JustADate(initDate){
  var utcMidnightDateObj = null
  // if no date supplied, use Now.
  if(!initDate)
    initDate = new Date();

  // if initDate specifies a timezone offset, or is already UTC, just keep the date part, reflecting the date _in that timezone_
  if(typeof initDate === "string" && initDate.match(/(-\d\d|(\+|-)\d{2}:\d{2}|Z)$/gm)){  
     utcMidnightDateObj = new Date( initDate.substring(0,10) + 'T00:00:00Z');
  } else {
    // if init date is not already a date object, feed it to the date constructor.
    if(!(initDate instanceof Date))
      initDate = new Date(initDate);
      // Vital Step! Strip time part. Create UTC midnight dateObj according to local timezone.
      utcMidnightDateObj = new Date(Date.UTC(initDate.getFullYear(),initDate.getMonth(), initDate.getDate()));
  }

  return {
    toISOString:()=>utcMidnightDateObj.toISOString(),
    getUTCDate:()=>utcMidnightDateObj.getUTCDate(),
    getUTCDay:()=>utcMidnightDateObj.getUTCDay(),
    getUTCFullYear:()=>utcMidnightDateObj.getUTCFullYear(),
    getUTCMonth:()=>utcMidnightDateObj.getUTCMonth(),
    setUTCDate:(arg)=>utcMidnightDateObj.setUTCDate(arg),
    setUTCFullYear:(arg)=>utcMidnightDateObj.setUTCFullYear(arg),
    setUTCMonth:(arg)=>utcMidnightDateObj.setUTCMonth(arg),
    addDays:(days)=>{
      utcMidnightDateObj.setUTCDate(utcMidnightDateObj.getUTCDate + days)
    },
    toString:()=>utcMidnightDateObj.toString(),
    toLocaleDateString:(locale,options)=>{
      options = options || {};
      options.timeZone = "UTC";
      locale = locale || "en-EN";
      return utcMidnightDateObj.toLocaleDateString(locale,options)
    }
  }
}


// if initDate already has a timezone, we'll just use the date part directly
console.log(JustADate('1963-11-22T12:30:00-06:00').toLocaleDateString())
// Test case from @prototype's comment
console.log("@prototype's issue fixed... " + JustADate('1963-11-22').toLocaleDateString())

Find elsewhere
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ javascript get a date without time | display example
Javascript get a date without time | Display Example - EyeHunts
May 15, 2021 - <!DOCTYPE html> <html> <body> <script> var d = new Date(); var NoTimeDate = d.getFullYear()+'/'+(d.getMonth()+1)+'/'+d.getDate(); alert(NoTimeDate); </script> </body> </html> ... Use split method: Split it by space and take the first part like ...
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ javascript-get-current-date-todays-date-in-js
JavaScript Get Current Date โ€“ Today's Date in JS
November 7, 2024 - const date = new Date(); console.log(date); // Fri Jun 17 2022 11:27:28 GMT+0100 (British Summer Time) Let's see how we can extract only the date from this long string. We'll make it more readable and understandable to users by using some JavaScript methods that operate on a date object. The date object supports numerous date methods, but for this article, we only need the current date and will only use three methods: getFullYear() โ€“ we will use this method to get the year as a four digit number (yyyy), for example 2022.
๐ŸŒ
Reddit
reddit.com โ€บ r/notion โ€บ how to get current date without time as a date object?
r/Notion on Reddit: How to get current date without time as a date object?
August 29, 2020 -

I'm trying to set up some formulas for database columns and have been struggling with getting today's date.

The problem with now() is that it returns the current date AND time, so if I have something like

prop("Due Date") == now() 

it will always return False except during the single minute that matches the time of now().

The closest I got was to use something like:

dateBetween(prop("Due Date"),now(),"days") == 0

but if something is <24 hours from now, it will return True even if it is tomorrow so it's impossible to differentiate between today and tomorrow.

Is there any way to strip the time from now()?

๐ŸŒ
UltaHost
ultahost.com โ€บ knowledge-base โ€บ get-current-date-time-javascript
How to Use JavaScript to Get the Current Date and Time | Ultahost Knowledge Base
March 7, 2025 - In this post, weโ€™ll look at different ways and techniques for acquiring the current date and time in JavaScript. In JavaScript, the Date object is the primary tool for handling dates and times similar to getting dates and times in Python. It provides various methods to create, manipulate, and format dates and times. The Date object can be created using the new keyword and it can represent any moment in time from the epoch (January 1, 1970) to the far future. Hereโ€™s how you can create a new JavaScript Date without time object representing the current date and time:
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-remove-time-from-date-typescript
How to remove Time from Date TypeScript?
The toISOString() method returns ... character to get only the date portion. var date = new Date(); var dateWithoutTime = date.toISOString().split('T')[0]; console.log(dateWithoutTime); On compiling, it will generate the same ...
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_dates.asp
JavaScript Dates
Date methods allow you to get and ... covered in the next chapters. JavaScript will (by default) output dates using the toString() method....
๐ŸŒ
GitHub
github.com โ€บ moment โ€บ moment โ€บ issues โ€บ 3455
How to represent dates (without time) and times (without date)? ยท Issue #3455 ยท moment/moment
September 19, 2016 - A Moment.js object (like its underlying Date object) always represents an exact point in time. Sometimes, however, I just want to store a date (say 2016-09-19). This is not a point in time, but a c...
Author ย  DanielSWolf
Top answer
1 of 16
789

.getMonth() returns a zero-based number so to get the correct month you need to add 1, so calling .getMonth() in may will return 4 and not 5.

So in your code we can use currentdate.getMonth()+1 to output the correct value. In addition:

  • .getDate() returns the day of the month <- this is the one you want
  • .getDay() is a separate method of the Date object which will return an integer representing the current day of the week (0-6) 0 == Sunday etc

so your code should look like this:

var currentdate = new Date(); 
var datetime = "Last Sync: " + currentdate.getDate() + "/"
                + (currentdate.getMonth()+1)  + "/" 
                + currentdate.getFullYear() + " @ "  
                + currentdate.getHours() + ":"  
                + currentdate.getMinutes() + ":" 
                + currentdate.getSeconds();

JavaScript Date instances inherit from Date.prototype. You can modify the constructor's prototype object to affect properties and methods inherited by JavaScript Date instances

You can make use of the Date prototype object to create a new method which will return today's date and time. These new methods or properties will be inherited by all instances of the Date object thus making it especially useful if you need to re-use this functionality.

// For todays date;
Date.prototype.today = function () { 
    return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}

// For the time now
Date.prototype.timeNow = function () {
     return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}

You can then simply retrieve the date and time by doing the following:

var newDate = new Date();
var datetime = "LastSync: " + newDate.today() + " @ " + newDate.timeNow();

Or call the method inline so it would simply be -

var datetime = "LastSync: " + new Date().today() + " @ " + new Date().timeNow();
2 of 16
548

To get time and date you should use

    new Date().toLocaleString();

>> "09/08/2014, 2:35:56 AM"

To get only the date you should use

    new Date().toLocaleDateString();

>> "09/08/2014"

To get only the time you should use

    new Date().toLocaleTimeString();

>> "2:35:56 AM"

Or if you just want the time in the format hh:mm without AM/PM for US English

    new Date().toLocaleTimeString('en-US', { hour12: false, 
                                             hour: "numeric", 
                                             minute: "numeric"});
>> "02:35"

or for British English

    new Date().toLocaleTimeString('en-GB', { hour: "numeric", 
                                             minute: "numeric"});

>> "02:35"

Read more here.

๐ŸŒ
Reddit
reddit.com โ€บ r/askprogramming โ€บ what's are best practices when dealing with dates, without time-of-day?
r/AskProgramming on Reddit: What's are best practices when dealing with dates, without time-of-day?
May 19, 2022 -

What is best practice when dealing with date values without time, in JavaScript? My concern is subtle off-by-one bugs caused by local Time Zone (TZ) offset (e.g. +5 hours), when doing date math.

JavaScript's built-in Date type represents a date and time not just the date. Internal representation is an integer of microseconds since 1970-01-01 00:00:00 UTC. Other languages, like Python, have separate Date and DateTime types. Java 8 introduced LocalDate.

You also have things like: new Date('5/18/2020') is local TZ (in US), but new Date('2022-05-18') is UTC. Same with Date.parse(string). And the time zone on most servers in UTC, whereas on the browser side the time zone will vary.

The date values will be used for simple date math in code and will be stored in a SQL database.

Possibilities:

  1. Use the an alternate type like integer value, of milliseconds or days (since 1970-01-01), or string in YYYYMMDD format.

  2. This was combined with #1

  3. Use Date ignoring time (as 00:00 local TZ). Convert from/to UTC when reading/writing to database

  4. Use Date with time as 00:00 UTC. Have to be careful not to mix with Date values in local TZ (e.g. now = new Date())

  5. Use Date in local TZ, but convert to UTC when read/writing to database. This is a variant of #3.

  6. Create a LocalDate class that enforces midnight.

  7. Use a library. js-joda has LocalDate.

I am leaning towards #3 and #6. Some code I am writing:

class LocalDate extends Date {
  // Error if time isn't midnight local TZ
  // Do not accept string in ISO format
  constructor(date?: Date|number|string)

  // Convert to 00:00 UTC
  // To be used before write to database
  toUtc(): Date

  // Only return date.  Also affects toJSON()
  toISOString(): string

  // Returns today's date at 00:00 Local TZ
  static today(): LocalDate
  // Set time to midnight local TZ, without error check.
  static fromDateTime(date: Date|number): LocalDate
  // Convert to local TZ.  Error if not 00:00 UTC.
  static fromUtc(date: Date|number): LocalDate
}

UPDATE:

Various edits.