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
๐ŸŒ
OpenReplay
blog.openreplay.com โ€บ common-date-time-operations-without-moment-js
Common date/time operations without Moment.js
May 23, 2023 - In conclusion, the JavaScript Date object is a powerful tool for working with date and time in JavaScript without relying on external libraries such as Moment.js. We have covered various ways to create and manipulate Date objects, including using the number of milliseconds since the epoch, the Date Time string, and date and time components.
Discussions

How to represent dates (without time) and times (without date)?
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... More on github.com
๐ŸŒ github.com
4
September 19, 2016
Javascript date method without time - Stack Overflow
Javascript method var d = new Date(); get datetime value, but how get clear date, without time ? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Comparing date part only without comparing time in JavaScript - Stack Overflow
What is wrong with the code below? Maybe it would be simpler to just compare date and not time. I am not sure how to do this either, and I searched, but I couldn't find my exact problem. BTW, whe... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Javascript Date - set just the date, ignoring time? - Stack Overflow
543 Comparing date part only without comparing time in JavaScript More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
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.

๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ javascript-get-date-without-time
How to get a Date without the Time in JavaScript | bobbyhadz
March 6, 2024 - 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.
๐ŸŒ
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
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-remove-time-from-date-typescript
How to remove Time from Date TypeScript?
September 4, 2023 - The toLocaleDateString() method returns a string representing the date portion of the Date object in the local time zone. It does not include the time portion. By default, it returns a string in the format "MM/DD/YYYY" (e.g., "05/05/2023"). ...
Find elsewhere
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())

๐ŸŒ
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 - The Date object in JavaScript comes with several methods that allow us to manipulate dates. One of these methods is toISOString(), which returns the date in the format of a string representing the date and time.
๐ŸŒ
DEV Community
dev.to โ€บ shubhampatilsd โ€บ removing-timezones-from-dates-in-javascript-46ah
Removing Timezones from Dates in Javascript - DEV Community
April 23, 2023 - I finally thought that this would be a great solution: store the output of .toLocaleString() and convert it to a Date again on the client, all without the timezone. However, when I implemented the solution in my React Native app, it didn't work. It kept telling me that I had passed an invalid date into the Date constructor. I searched on the internet. Then, I found this on the MDN Web Docs: This gave me a hint as to why the code worked in my browser but not my React Native app. The JS in Firefox was running on a different runtime than React Native. Since JavaScript is so uncoordinated, JS code typically runs in a specific environment called an engine.
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ javascript-create-date-without-timezone
How to Create a Date without Timezone in JavaScript | bobbyhadz
March 6, 2024 - This is because my time zone is 3 hours ahead of Coordinated Universal time (UTC). To create a Date without the timezone, we called the toISOString() method on the Date object and removed the character Z from the ISO string.
Top answer
1 of 4
4

What is it that you actually want to achieve? If you want to show the timestamps always as they are ignoring timezone information, you might make things quite confusing to the user when those timestamps might show future time to some of the users. For example: someone modifies data and another user in US west coast views the data and sees the timestamp pointing to the future.

Maybe something you wan to use is Data.toUTCString(), that shows the timestamp so that you will have GMT as a timezone. Then it will be clear that to the users that this timestamp is not in their timezone. Also you might want to have timezone information appended to the timestamp string so that the conversions happen correctly. If you your timestamps are in UTC (or Zulu time) you can add "Z" to the end of the string. RFC 2822 Section 3.3 defines that date and time should express local time, but at least with node.js if you leave timezone information out, it seems to express UTC time. So adding the timezone information will make your life easier (would be even better if you would add timezone information in the in the string that you store in your database).

As an example:

var timestamp = "2016-10-11T11:09:00";
var d = new Date(timestamp);
// or
d = new Date(timestamp + "Z");

// Then showing the date
d.toString();
// or without the converting it to user's local timezone
d.toUTCString();

I hope this helps.

2 of 4
2

You can use Moment.js and define your own custom date formatter:

var formatter= 'YYYY-MM-DD[T]HH:mm:ss';
var date = new Date('July 17, 2018 03:24:00');
var time = moment(date).format(formatter);
console.log('Time: ',time);

Fiddle: https://jsfiddle.net/mkotsollaris/3krdttm3/

Top answer
1 of 8
89

Here's a moment.js solution for 12 or 24 hour times:

moment('7:00 am', ['h:m a', 'H:m']); // Wed Dec 30 2015 07:00:00 GMT-0600 (CST)
moment('17:00', ['h:m a', 'H:m']);   // Wed Dec 30 2015 17:00:00 GMT-0600 (CST)
moment('17:00 am', ['h:m a', 'H:m']);// Wed Dec 30 2015 17:00:00 GMT-0600 (CST)
moment('17:00 pm', ['h:m a', 'H:m']);// Wed Dec 30 2015 17:00:00 GMT-0600 (CST)

http://momentjs.com/docs/#/parsing/string-formats/

2 of 8
26

Unfortunately, there's not a great solution. JavaScript only has a Date object, which is probably misnamed since it is really a date+time.

One thing you might want to think about deeper - you say you want to work with only time, but do you mean a time-of-day or do you mean a duration of time? These are two related, but slightly different concepts.

For example, you said you might want an operation like "15:00 + 1 hour". Well that would clearly be 16:00 either way. But what about "15:00 + 10 hours"? It would be 25:00 if you are talking about a duration, but it might be 01:00 if you are talking about time-of-day.

Actually, it might not be 01:00, since not all days have 24 hours in them. Some days have 23, 23.5, 24.5, or 25 hours, depending on what time zone and whether DST is starting or stopping on that day. So in the time-of-day context, you probably do want to include a particular date and zone in your calculation. Of course, if you are talking about straight 24-hours days, then this point is irrelevant.

If you are talking about durations - you might want to look again at moment.js, but not at the moment object. There is another object there, moment.duration. The reference is here.

And finally, you might want to consider just using plain javascript to parse out hours and minutes from the time string as numbers. Manipulate the numbers as necessary, and then output a string again. But your question seems like you're looking for something more managed.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-remove-time-from-date-with-momentjs
How to Remove Time From Date with Moment.js? - GeeksforGeeks
July 23, 2025 - ... const moment = require('moment'); let date = moment('2023-07-13T15:22:10'); let formattedDate = date.format('YYYY-MM-DD'); console.log(formattedDate); ... In this approach we are using the toDate() method.
๐ŸŒ
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()?

๐ŸŒ
Reddit
reddit.com โ€บ r/javascript โ€บ [askjs] get difference between datetime without timezone reference
r/javascript on Reddit: [AskJS] Get difference between datetime without timezone reference
November 12, 2023 -

Hello,
Is it possible to get the difference between 2 datetime if I dont have reference of the timezone?
From the API I get the datetime like 2023-11-14T08:30:00 for departure and 2023-11-14T12:45:00 for arrival.
By looking at it, the difference will be 4hr and 15min. But the flight is from Dubai to Los Angeles which should be 16hr and 15min.
I will have occations that I will get timezone will be + or -.