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 OverflowTry 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)
Try this:
var nowDate = new Date();
var date = nowDate.getFullYear()+'/'+(nowDate.getMonth()+1)+'/'+nowDate.getDate();
Note: Adjust format as you want, like reorder day, month, year, remove '/' and get combined date etc.
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.
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())
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:
Use the an alternate type like integer value, of milliseconds or days (since 1970-01-01), or string in
YYYYMMDDformat.This was combined with #1Use
Dateignoring time (as 00:00 local TZ). Convert from/to UTC when reading/writing to databaseUse
Datewith time as 00:00 UTC. Have to be careful not to mix withDatevalues in local TZ (e.g.now = new Date())Use
Datein local TZ, but convert to UTC when read/writing to database. This is a variant of #3.Create a
LocalDateclass that enforces midnight.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.
For complete reference of parsing date Follow link here
You can simply parse only date from you variable like
d.toJSON().substring(0,10)
or
d.toDateString();
I would advise you to use dayjs or momentjs (http://momentjs.com/) for all your javascript problems concerning dates.
This code will reset hours, minutes, seconds, milliseconds of your javascript date object.
var d = new Date();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
Or in a simplified way:
var d = new Date();
d.setHours(0, 0, 0, 0);
Or as a one line function:
function now () { const d = new Date(); d.setHours(0, 0, 0, 0); return d }
now(); // returns the current date
Without conversion, and you still have a date object at the end.
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") == 0but 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()?
How about .toDateString()?
Alternatively, use .getDate(), .getMonth(), and .getYear()?
In my mind, if you want to group things by date, you simply want to access the date, not set it. Through having some set way of accessing the date field, you can compare them and group them together, no?
Check out all the fun Date methods here: MDN Docs
Edit: If you want to keep it as a date object, just do this:
var newDate = new Date(oldDate.toDateString());
Date's constructor is pretty smart about parsing Strings (though not without a ton of caveats, but this should work pretty consistently), so taking the old Date and printing it to just the date without any time will result in the same effect you had in the original post.
new Date().toISOString().split('T')[0]
Use new Date() to generate a new Date object containing the current date and time.
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = mm + '/' + dd + '/' + yyyy;
document.write(today);
This will give you today's date in the format of mm/dd/yyyy.
Simply change today = mm +'/'+ dd +'/'+ yyyy; to whatever format you wish.
var utc = new Date().toJSON().slice(0,10).replace(/-/g,'/');
document.write(utc);
Use the replace option if you're going to reuse the utc variable, such as new Date(utc), as Firefox and Safari don't recognize a date with dashes.