match two datetimes in javascript not working [duplicate] - javascript

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 9 years ago.
I have two dates :
date1 = "2013-07-08 12:30:00"
date2 = "2013-07-08 13:30:00"
Now in javascript i want to match these two dates and its they dont match than i want to delete the appointment and if they match than nothing to do.
I tried this code but its not working :
if(date1 == date2)// Event already exists
{
// do nothing
}
else
{
// delete the record.
}
I tried to compare with "new Date(date1) == new Date(date2)" also but its not working either.
There is some problem in my code or date format. can anyone know how to do this and where i am wrong in this code ?
Thanks in advance.

Two different objects are never the same, you have to compare the numbers that make up the unix timestamp:
var date1 = "2013-07-08 12:30:00",
date2 = "2013-07-08 13:30:00";
var d1 = new Date(date1);
var d2 = new Date(date2);
if (d1.getTime() == d2.getTime()) {
}
FIDDLE

it works for me:
var date1 = "2013-07-08 12:30:00";
var date2 = "2013-07-08 12:30:00";
var date3 = "2013-07-08 12:00:00";
console.log(date1 == date2); //true
console.log(date1 == date3); //false
Jsfiddle link

Adeno has a valid answer but will fail if the dates are milliseconds appart (not the case in OP's example if you use a valid date string). To be sure you're comparing dates by minutes or days you can do:
function sameTime(dt1,dt2){
//round the dates to the minutes
var t1=new Date(dt1);
var t2=new Date(dt2);
t1.setSeconds(0,0);
t2.setSeconds(0,0);
return t1.toString()===t2.toString();
}
function sameDay(dt1,dt2){
//round the dates to the day
var t1=new Date(dt1);
var t2=new Date(dt2);
t1.setHours(0,0,0,0);
t2.setHours(0,0,0,0);
return t1.toString()===t2.toString();
}
function sameMonth(dt1,dt2){
//round the dates to the month
var t1=new Date(dt1);
var t2=new Date(dt2);
t1.setHours(0,0,0,0);
t2.setHours(0,0,0,0);
t1.setDate(1);
t2.setDate(1);
return t1.toString()===t2.toString();
}
var date1 = "2013-07-08T12:30:00",
date2 = "2013-07-08T13:30:00";
var d1 = new Date(date1);
var d2 = new Date(date2);
console.log(sameTime(d1,d2));//precise to the minute
console.log(sameDay(d1,d2));//precise to the day
console.log(sameMonth(d1,d2));//precise to the month

Related

Comparing Dates in NodeJS IF Statement

I am using nodejs/javascript and trying to compare two dates to each other in order to apply a specific style if the date is before the set date.
Here is what I have:
var d = new Date();
var date = d.getMonth()+1+'/'+d.getDate()+'/'+(d.getFullYear().toString().substr(-2)-1);
var da = new Date('1/4/18');
var da_test = da.getMonth()+1+'/'+da.getDate()+'/'+(da.getFullYear().toString().substr(-2));
if(da_test < date) {
// do something
}
date_test is currently returning the date from a year ago today, 1/23/18. I have set the other date that it will compare itself to, to 1/4/18. While this should be true, for some reason it is not whenever the IF statement runs. However, if I change the date to something like 1/2/18, then it returns true. How is that the case and how can it be changed so it will return true if it is any date before 1/23/18?
You can compare those two dates like this:
const d1 = new Date('1/23/18');
const d2 = new Date('1/4/18');
if (d2 < d1) ...
In your code example you are comparing two Strings
You can compare the milliseconds since epoch (the number of milliseconds since 1 January 1970 00:00:00)
const d1 = new Date('1/23/18');
const d2 = new Date('1/4/18');
if (d2.getTime() < d1.getTime()) {
}
You can also compare ISO date strings
const d1 = new Date('1/23/18');
const d2 = new Date('1/4/18');
if (d2.toISOString() < d1.toISOString()) {
}

javascript comparing date formats [duplicate]

This question already has answers here:
compare string with today's date in JavaScript
(8 answers)
Closed 4 years ago.
I am trying to compare dates with different formats. I see wrong results when I compare the below, How can I converts dates to a standard format to get correct results.
Heres my Fiddle
var date1 = "4/12/2018 9:52:21 PM";
var date2 ="4/12/2018 9:52:51 PM";
var date3 ="2018/04/12 21:54:40";
var dateCondition1 = (date3>date2);
var dateCondition2 = (date2>date1);
alert(dateCondition1); //shows wrong result
alert(dateCondition2); //shows right result
will this be a correct comparison?
var date1 = new Date("4/12/2018 9:52:21 PM");
var date2 =new Date("4/12/2018 9:52:51 PM");
var date3 =new Date("2018/04/12 21:54:40");
var dateCondition1 = (date3>date2);
var dateCondition2 = (date2>date1);
alert(dateCondition1); //shows wrong result
alert(dateCondition2); //shows right result
try with pure javascript:
var date1 = new Date("4/12/2018 9:52:21 PM");
var date2 =new Date("4/12/2018 9:52:51 PM");
var date3 =new Date("2018/04/12 21:54:40");
var dateCondition1 = (date3.getTime() > date2.getTime());
var dateCondition2 = (date2.getTime() > date1.getTime());
alert(dateCondition1);
alert(dateCondition2);
in the first block of code you are comparing strings
"4/12/2018 9:52:21 PM" > "4/12/2018 9:52:21 PM";
in the second block of code the comparison is correct,
Why does a boolean return in the comparison of 2 strings?
"Matt Ball"
Because, as in many programming languages, strings are compared lexicographically.
You can think of this as a fancier version of alphabetical ordering, the difference being that alphabetic ordering only covers the 26 characters a through z.
ALTERNATIVE
using the library moment js is easier
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script>
//Currrent Date
var now = moment(),
custom = moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A');
document.write("Compare dates=>" + now.isAfter(custom));
</script>
if you want to use the three comparisons you can format the dates as you want
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script>
var now = moment();
var date1 = moment('4/12/2018 9:52:21 PM','DD/MM/YYYY hh:mm:ss A');
var date2 = moment('4/12/2018 9:52:51 PM','DD/MM/YYYY hh:mm:ss A');
var date3 = moment('2018/04/12 21:54:40','YYYY/DD/MM hh:mm:ss A');
var dateCondition1 = (date3.isAfter(date2));
var dateCondition2 = (date2.isBefore(date1));
alert(dateCondition1);
alert(dateCondition2);
</script>
</html>

Compare a date in string format with todays date

I know this has been asked before but I can't get it to work due to my date format, which I can't change. Any help would be appreciated.
My date is in this format;
4/11/2017 12:30 PM.
If I inspect it in the developer tools it shows it as
4/11/2017 12:30 PM EDIT: Won't show with prepended space here
i.e. with a space in front, not sure if that's relevant.
Does anyone know if it's possible or how to compare it with today's date to see if it's in the past or future?
I've tried tinkering with the following code but can't get it to work because of the time, PM, and forward slashes.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d,m,y);
mydate=new Date('13/04/2017');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
If you have dates that are in the same format of something like 13/04/2017, you could split the string based on the slashes and compare the values starting from the right moving left.
By this, I mean when you have your array of three values for each date, you could first compare the year, if that's the same, move on to comparing the month, if that's the same then on to comparing the day.
But if for instance one of the year's is 2018 while the other is 2016, you would immediately know that the 2018 one comes later.
var st = "19/05/2019";
var st2 = "19/05/2019";
function provideLaterDate(date1, date2) {
var splitDateDate1 = date1.split("/").reverse();
var splitDateDate2 = date2.split("/").reverse();
var laterDate = false;
splitDateDate1.forEach(function(val, idx, arr) {
if ( laterDate === false ) {
if ( val > splitDateDate2[idx] ) {
laterDate = splitDateDate1;
} else if ( val < splitDateDate2[idx]) {
laterDate = splitDateDate2;
} else {
laterDate = "Both are the same";
}
}
});
if ( /\//.test(laterDate) ) {
return laterDate.reverse().join("/");
} else {
return laterDate;
}
}
To get rid of the "time pm" part, you could simply do something like:
// Assuming your date has a structure like this: 4/11/2017 12:30 PM.
var newDate = unformattedDate.split(" ")[0];
// This will separate your date string by spaces, and since there are no spaces until after the year in your date, the 0 index will give you the date minus the time and pm portion. Please pardon the not-consistent variable names.
The problem was with the way you were constructing date. Construct date like this var mydate = new Date(2017, 04, 03); and it works.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d, m, y);
var mydate = new Date(2017, 04, 03);
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
}
else {
alert("smaller")
}
You can split the date. Be aware you should contruct your date as follows:
var date = new Date(y,m,d);
Means year first, then month and finally day, as you can see under https://www.w3schools.com/jsref/jsref_obj_date.asp
You can use the following code to perform what you want:
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(y,m,d);
newdate = '13/04/2017'
array = newdate.split('/');
var d1 = array[0]
var m1 = array[1]-1
var y1 = array[2]
mydate = new Date(y1,m1,d1);
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can always check the date created is correct by using the date.toString() function. Be aware 0=January for month as you can check under https://www.w3schools.com/jsref/jsref_getmonth.asp. That's why I added the -1 for var m1.
Problem:
It's not working because you are comparing a date with an Invalid date, it will always return false.
Explanation:
And the Invalid date comes from the line new Date('13/04/2017'), because 13 is expected to be a month number and not a day which is an invalid month, because the new Date(stringDate) will be treated as a local Date and not a UTC date by the browser, and it depends on which browser you are using.
You can see in the JavaScript Date Specification that:
parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
Demo:
So if we change new Date('13/04/2017') to new Date('04/13/2017') the code will work as expected:
var date = new Date();
var mydate = new Date('04/13/2017');
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
} else {
alert("smaller")
}
if(date.getTime()>mydate.getTime()){
alert("greater");
}
else if (date.getTime()==mydate.getTime){
alert("simmilar");
else {alert("smaller");}

Date format to dd/mm/yyyy in a single object [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 9 years ago.
I know that date format "dd/mm/yyyy" can be achieved like this:
var d = new Date();
var day = d.getDate();
var month = (d.getMonth() +1);
var year = d.getFullYear();
document.write("Today is " +day+ "/" +month+ "/" +year+ "<br>");
Date picker
var x = new Date(document.getElementById("dateSelection"));
However how can I convert those to a single date object so I can then compare it against date picker in a simple statement like this:
if (d > x)
{
document.write("Date from the past");
}
else if (d < x)
{
document.write("Date from the future");
}
else
{
document.write("Date equals today's date");
}
Thanks for help I'm novice at this.
You are passing the dateSelection element to new Date, not its value. Date wants a string as its parameter, not a DOMElement.
Try this:
var x = new Date(document.getElementById("dateSelection").value);
Use a handy dandy prototype to convert the string to a date:
String.prototype.toDate=function(){
var mo = parseInt(this.substr(0,2)) -1
var dy = this.substr(3,2)
var yr = this.substr(6,4)
var dt = new Date(yr, mo, dy, 0, 0, 0, 0)
return dt
}
var s = '01/01/2014'
var d = s.toDate()
Now you have a date and can do date comparisons.

Comparing two dates with javascript or datejs (date difference)

I am trying to compare two dates which are in Finnish time form like this: dd.mm.YYYY or d.m.YYYY or dd.m.YYYY or d.mm.YYYY.
I am having a hard time finding out how to do this, my current code won't work.
<script src="inc/date-fi-FI.js" type="text/javascript"></script>
<script type="text/javascript">
function parseDate() {
var date = $('#date').val();
var parsedDate = Date.parse(date);
alert('Parsed date: '+parsedDate);
}
function jämförMedIdag (datum) {
if (datum == null || datum == "") {
alert('Inget datum!');
return;
}
/*resultat = Date.compare(Datum1,Datum2);
alert(resultat); */
var datum = Date.parse(datum);
var dagar = datum.getDate();
var månader = datum.getMonth();
var år = datum.getYear();
var nyttDatum = new Date();
nyttDatum.setFullYear(år,månader,dagar);
var idag = new Date();
if(nyttDatum>idag) {
var svar = nyttDatum - idag;
svar = svar.toString("dd.MM.yyyy");
alert(svar);
return(svar);
} else {
var svar = idag - nyttDatum;
svar = svar.toString("dd.MM.yyyy");
alert(svar);
return(svar);
}
}
</script>
This code will try to calculate the difference between two dates, one of them being today. No success lolz.
Thanks in advance!
My final code (thanks RobG!):
function dateDiff(a,b,format) {
var milliseconds = toDate(a) - toDate(b);
var days = milliseconds / 86400000;
var hours = milliseconds / 3600000;
var weeks = milliseconds / 604800000;
var months = milliseconds / 2628000000;
var years = milliseconds / 31557600000;
if (format == "h") {
return Math.round(hours);
}
if (format == "d") {
return Math.round(days);
}
if (format == "w") {
return Math.round(weeks);
}
if (format == "m") {
return Math.round(months);
}
if (format == "y") {
return Math.round(years);
}
}
It is not fully accurate, but very close. I ended up adding some addons to it to calculate in day week month year or hour, anyone can freely copy and use this code.
If you are using Datejs, and the optional time.js module, you can run your calculations with the following code by creating a TimeSpan object:
Example
// dd.mm.YYYY or d.m.YYYY
// dd.m.YYYY or d.mm.YYYY
var start = Date.parse("20.09.2011");
var end = Date.parse("28.09.2011");
var span = new TimeSpan(end - start);
span.days; // 8
Of course the above could be simplified down to one line if you really want to be extra terse.
Example
new TimeSpan(Date.parse(end) - Date.parse(start)).days; // pass 'end' and 'start' as strings
Hope this helps.
If your dates are strings in the common form d/m/y or some variation thereof, you can use:
function toDate(s) {
var s = s.split('/');
return new Date(s[2], --s[1], s[0]);
}
You may want to validate the input, or not, depending on how confident you are in the consistency of the supplied data.
Edit to answer comments
To permit different separators (e.g. period (.) or hyphen (-)), the regular expression to split on can be:
var s = s.split(/[/\.-]/);
The date will be split into date, month and year numbers respectively. The parts are passed to the Date constructor to create a local date object for that date. Since javascript months are zero indexed (January is 0, February is 1 and so on) the month number must be reduced by one, hence --s[1].
/Edit
To compare two date objects (i.e get the difference in milliseconds) simply subtract one from the other. If you want the result in days, then divide by the number of milliseconds in a day and round (to allow for any minor differences caused by daylight saving).
So if you want to see how many days are between today and a date, use:
function diffToToday(s) {
var today = new Date();
today.setHours(0,0,0);
return Math.round((toDate(s) - today) / 8.64e7);
}
alert(diffToToday('2/8/2011')); // -1
alert(diffToToday('2/8/2012')); // 365
PS. The "Finnish" data format is the one used by the vast majority of the world that don't use ISO format dates.
Using the Date object:
var today = Date.today();
var dateToday = Date.parse(today.toString('MMMM d, yyyy'));
var prevMonthDate = dateToday.addDays(-30);
var difference = (dateToday - prevMonthDate)/86400000;
console.log(difference); //will give you the difference in days.

Categories