javascript compare two dates and throw an alert - javascript

I have two dates in DD/MM/YYYY HH:MM:SS format ,i want to compare two dates and throw an
alert .
I tried the below code,but it is not working.
startdate = "14/12/2014 19:00:00";
enddate = "21/01/2015 19:00:00";
if(new Date(startdate) > new Date(enddate))
{
alert("End date cannot be less than start date");
}

You can create a Date using the following constructors:
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, date[, hour[, minutes[, seconds[, milliseconds]]]]]);
You have used the third of them, where the dateString is a
String value representing a date. The string should be in a format
recognized by the Date.parse() method (IETF-compliant RFC 2822
timestamps and also a version of ISO8601).
The string you have provided hasn't the correct format. Hence the corresponding date objects haven't been created.
I would prefer using the last constructor, since I wouldn't have to format correspondingly the strings.
var startDate = new Date(2014,12,14,19,0,0);
var endDate = new Date(2015,1,21,19,0,0);
I swapped the startDate with the endDate, in order we see the alert.
var endDate = new Date(2014,12,14,19,0,0);
var startDate = new Date(2015,1,21,19,0,0);
if(startDate > endDate)
{
alert("End date cannot be less than start date");
}

Related

What the elegant way to convert date in string to Date object?

I have this date in string format:
"05/2016" or "12/2015"
How can I convert the dates above in string format to Date() javascript object?
Date constructor accepts params in next order: year, month, day, hours, minutes, seconds, milliseconds, so simply parse string and pass it into Date constructor.
var data = "05/2016".split('/');
// Add + before year to convert str into number. Decrease second param because month starts from 0..11.
var date = new Date(+data[1],data[0] - 1);
console.log(date);
Also, you can convert your string to format which would be parsed correctly by new Date ( See more about dateString in MDN Date.parse description.
// convert string "05/2016" -> "2016-05"
var dateString = "05/2016".split('/').reverse().join('-');
var date = new Date(dateString);
console.log(date);
The previous answers are not correct - they get either the month or the year wrong. This is right (see the comment by Frédéric Hamidi)
var str = "12/2015";
var arr = str.split('/');
var date = new Date(parseInt(arr[1], 10), parseInt(arr[0], 10)-1)
console.log(date)
You can split string to get an array then use Date constructor.
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
var str = "12/2015";
var arr = str.split('/');
var date = new Date(parseInt(arr[1], 10), parseInt(arr[0], 10) - 1)
console.log(date)
You might want to look at Converting string to date in js
I had a similar issue and stumbled upon this existing link.

Convert LocaleTimeString Back to Date

Firstly, I convert a datetime to date and time respectively.
var d = new Date();
var localeDate = d.toLocaleDateString();
var localeTime = d.toLocaleTimeString();
However, when i try to convert it back to date object
var convertLocaleDate = new Date(localeDate); // success
var convertLocaleTime = new Date(localeTime); // not a valid date format
How can i convert localeTime back to valid date?
look carefully. You are not converting localeDate back to the original date. The time portion is set to 00:00:00
You cannot achieve the result you are trying for.
new Date() will work for the arguments mentioned below
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
more info here :
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date
giving localeTime as an argument doesn't work because the Date constructor will not know what date/month/year that time is for.
On the other hand localeDate worked because the date/month/year were known and time was set as default to 12am as default

getTime() in AngularJS , error in new Date(date) in Java Script

$scope.notAvailableDayClick=function(val1,date){
console.log("day clcik")
var startDate=$filter('date')(date,'yyyy-MM-dd')
var endDate=new Date(startDate)
endDate.setMinutes(59)
endDate.setHours(23)
}
date is 2015-01-16
if I do this
new Date(date)
Thu Jan 15 2015 16:00:00 GMT-0800 (Pacific Standard Time)
So I have to go with AngularJS
var startDate=$filter('date')(date,'yyyy-MM-dd')
but now I need startDate.getTime(), error occur I think it takes it as a String
As per angular docs the filter returns a String in requested format. Date constructor accepts ISO8601 formats usually although some browsers support many formats as I remember. Probably your format yy-MM-dd is not supported.
I hope the variable date is a valid Date object, in that case why don't you use it instead of the formatted string you made with angular filter?
var endDate = new Date(date);
endDate.setMinutes(59);
endDate.setHours(23);
Also you have a Date constructor that accepts the format
new Date(year, month[, date[, hour[, minutes[, seconds[, milliseconds]]]]]);
So if what you have in hand is 2015-01-16 you can get midnight of that day with:
var startDate = "2015-01-16";
var year = parseInt(startDate.split('-')[0], 10);
var month = parseInt(startDate.split('-')[1], 10) - 1;
var year = parseInt(startDate.split('-')[2], 10);
var endDate = new Date(year, month, date, 23, 59);
Just use the original date to create endDate not the angular filtered version
var endDate=new Date(date);
endDate.setMinutes(59);
endDate.setHours(23);
Best option is to use ISO-String, because Google Chrome supports this format: MM-dd-yyyy. In Mozilla this format gives Invalid Date.
new Date('MM-dd-yyyy')
So using Iso-String in Angular, it can done as follows:
new Date($filter('date')(yourdDate,'yyyy-MM-ddTHH:mm:ss.sssZ'))

What is wrong with this javascript date difference calculate function?

Any idea why this function doesn't work properly in Internet Explorer?
function days_between(check_in, check_out)
{
var oneDay = 24*60*60*1000;
var firstDate = new Date(check_in);
var secondDate = new Date(check_out);
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));
return diffDays;
}
in internet explorer it shows NaN as result.
im calling this function in this date format
var check_in = "2012-02-09";
var check_out = "2012-02-12";
var range = days_between(check_in, check_out);
Regards
IE doesn't support Date.parse or passing "2012-02-09" (with ISO dates) to new Date, you need to parse it yourself and pass new Date( 2012, 1, 9 ) or use a Date.parse shim for ISO dates
The date format you're passing (yyyy-mm-dd) isn't supported by Date. See the note here that says it must be in a format parsable by parse. See here for acceptable parse formats: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse
You have problem in creating the Date Object
Date objects are created with the Date() constructor.
There are four ways of instantiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Most parameters above are optional. Not specifying, causes 0 to be passed in.
Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time.
All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
Some examples of instantiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)
(Taken from http://www.w3schools.com/js/js_obj_date.asp)
You are giving the date arguments in an incorrect format. You can expect javascript to support these formats:
MM-dd-yyyy
yyyy/MM/dd
MM/dd/yyyy
MMMM dd, yyyy
MMM dd, yyyy
To fix your immediate problem, you can use replace() to format your arguments.
function days_between(check_in, check_out)
{
var firstDate = new Date(check_in.replace('-' , '/'));
var secondDate = new Date(check_out.replace('-' , '/'));
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime()) / 86400000);
return diffDays;
}
And by the way, you can replace oneDay with a constant.

Javascript to compare two dates, from strings, begin <= end

I get two strings formated like (Brazilian Format): "DD/MM/YYYY", I need to compare both. Since the first field is the begin and the last is the end,
My validation is begin <= end
Date.new(begin) is generating 'invalid date' even on ISO !
Don't use Date.new. Use new Date(). Because of the format of your date string, I would recommend grabbing each field individually and passing them into the constructor:
var startYear = parseInt(document.getElementById('startYear'), 10);
var startMonth = parseInt(document.getElementById('startMonth'), 10) - 1; // as per Residuum's comment
var startDay = parseInt(document.getElementById('startDay'), 10);
var start = new Date(startYear, startMonth, startDay);
etc. If you're handed a date string, then you can use fuzzy lollipop's method to get each field from the string. I'm not sure if the Date constructor will accept unparsed strings for the individual fields, however.
The, once you have the two dates you'd like to compare, just compare their values in milliseconds since the epoch:
function isValid(start, end) {
return start.getTime() < end.getTime();
}
There's a nice date handling library called datejs which has a parseExact(dateStr, format) method.
you can do this, if you know your date will always be formatted the same way dd/mm/yyyy
today = "23/02/1001";
dateComponents = today.split("/");
date = new Date(dateComponents[2], dateComponents[1] - 1, dateComponents[0]);
but a better solutions is to look at this page there is Datejs which is a good alternative to date processing.
Quick 'n dirty :
function is_valid (start , end) {
return start.split('/').reverse().join('') <= end.split('/').reverse().join('') ;
}
That is, split the date into components, reverse the order join them again and do a string comparison.
Edit: As noted in the comment, of course this won't work if your month/days smaller than 10 are not zero padded.
The new 'hotness' in JS time world: http://momentjs.com/
Fits this use-case as well
Here are all available constructors for date objects in Javascript:
dateobject = new Date(); // returns date of current time stamp
// on the browser
dateobject = new Date("Month Day, Year Hours:Minutes:Seconds");
dateobject = new Date(Year, Month, Day);
dateobject = new Date(Year, Month, Day, Hours, Minutes, Seconds);
dateobject = new Date(Milliseconds);
Pick the one you try to use, but I would go for new Date(Year, Month, Day); in your case.
EDIT:
Note: Monthis zero-based in Javascript, so January 1 2010, will be new Date(2010, 0, 1) and December 31 2011 is new Date(2010, 11, 31).

Categories