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

🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-get-date-without-time
How to get a Date without the Time in JavaScript | bobbyhadz
The method changes the date's time components in place. The setHours method takes values for the hours, minutes, seconds and milliseconds as parameters. We set all values to 0 to get a date without the time.
🌐
Talkerscode
talkerscode.com › howto › getting-date-without-time-in-javascript.php
Getting Date Without Time In JavaScript
We log the dateWithoutTime value to the console, which represents the current date without the time component.
🌐
W3Schools
w3schools.com › js › js_dates.asp
JavaScript Dates
JavaScript stores dates as number of milliseconds since January 01, 1970. Zero time is January 01, 1970 00:00:00 UTC.
🌐
IQCode
iqcode.com › code › javascript › javascript-get-date-without-time
javascript get date without time Code Example
function WithoutTime(dateTime) { var date = new Date(dateTime.getTime()); date.setHours(0, 0, 0, 0); return date; }
🌐
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);...
🌐
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 ...
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › how-to-remove-time-from-date-typescript
How to remove Time from Date TypeScript?
The toDateString() method is then ... YYYY" (e.g., "Thu May 05 2023"). var date = new Date(); date.setHours(0, 0, 0, 0); var dateWithoutTime = date.toDateString(); console.log(dateWithoutTime); On compiling, it will generate the ...
🌐
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 calendar day. Depending on my time zone, ...
Author   DanielSWolf
🌐
W3Schools
w3schools.com › js › js_date_methods.asp
JavaScript 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().
🌐
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.

🌐
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 - 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.
🌐
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()?

🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types
Date and time
If we only want to measure time, we don’t need the Date object. There’s a special method Date.now() that returns the current timestamp.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date › Date
Date() constructor - JavaScript | MDN
Note: Date() can be called with or without new, but with different effects. See Return value. There are five basic forms for the Date() constructor: When no parameters are provided, the newly-created Date object represents the current date and time as of the time of instantiation.