I have two date in which one is dd-mm-yyyy hh:mm
format and another in dd-mm-yyyy (D1)
format
fristly i split the dd-mm-yyyy hh:mm
fo
var now = new Date();
var end = new Date(//some other date hear);
if(now>end)
{
console.log('now=',now);
}
else
{
console.log('end=',end);
}
Try:
var msg = new Date("03-05-2014").getTime() >= new Date("28-04-2014 00:00").getTime() ? 'Correct' : 'Wrong';
alert(msg);
This is you need actually
var D1 = "03-05-2014";
var D2 = "28-04-2014 00:00";
if ((new Date(D1).getTime()) >= (new Date(D2).getTime())) {
alert('correct');
} else {
alert('wrong');
}
WORKING DEMO
Convert them into milliseconds, then do comparision
That is a string comparison you are doing, not a date comparison
In terms of strings... 2 is greater than 0... That's why you always hit the "something is wrong" statement
EDIT: This is an explanation of what went wrong // Creates a date variable var D1 = new Date();
// Creates another date variable
var D2 = new Date();
// Converts this date variable into a string
D1 = 03-05-2014
// This is too is converted into a string
D2 = 28-04-2014 00:00
dat = D2.split(' ');
D2 = dat[0];
//finally D2 is 28-04-2014 <-- true, but it is a string
if(D2<=D1){ // <-- At this point you are doing a string comparison
echo "ok";
} else {
echo "something is wrong";
}
EDIT: This is a possible solution. . .
Instead of that, do this
var D1 = new Date();
var D2 = new Date();
if(D2.getTime() <= D1.getTime()){
echo "ok";
} else {
echo "something is wrong";
}
EDIT: If you are getting it from an input field, then do this
// Make sure you dates are in the format YYYY-MM-DD.
// In other words, 28-04-2014 00:00 becomes 2014-04-28 00:00
// Javascript Date only accepts the ISO format by default
var D1 = new Date( $('#input1#').val() );
var D2 = new Date( $('#input2#').val() );
if(D2.getTime() <= D1.getTime()){
echo "ok";
} else {
echo "something is wrong";
}
You can date compare as most simple and understandable way like.
<input type="date" id="getdate1" /> //with time include
<input type="date" id="getdate2" /> // without time include
so firstly write a common method to parse date method.
<script type="text/javascript">
function parseDate(input) {
var parts = input.split(' ');
var datecomp=parts[0]; // will get
var timecomp=parts[1]; // will get time
var dparts=datecomp.split('-');
if(timecomp!=undefined && timecomp!=null){ //if there is like
var tparts=timecomp.split(':');
return new Date(dparts[2], dparts[1]-1, dparts[0], tparts[0], tparts[1]);
}else{ // for when no time is givin
return new Date(dparts[2], dparts[1]-1, dparts[0]);
}
return "";
}
</script>
by here you can call above method
<script type="text/javascript">
$(document).ready(function(){
//parseDate(pass in this method date);
Var Date1=parseDate($("#getdate1").val());
Var Date2=parseDate($("#getdate2").val());
//use any oe < or > or = as per ur requirment
if(Date1 = Date2){
return false; //or your code {}
}
});
</script>
Just use parseDate method and compare any type of the date.