javascript dates compare - javascript

I'm working with javascript Date and i'm starting to go crazy :)
I want two compare only the year,month, day of two dates. The date are (retrieve from firebug stacktrace):
[Date {Thu Feb 11 2010 12:00:00 GMT+0000 (GMT Standard Time)}]
[Date {Sun Jul 11 2010 00:00:00 GMT+0100 (GMT Daylight Time)}]
In this point i'm trying compare the two dates like this:
if (datepickerBegin == null || datepickerBegin.length == 0 || datepickerBegin != date) {
//Do stuff
}
This code obvious doesn't work, which is the simple way of comparing these two String?
I'm trying to convert this var to Date and concatenate into another var the getMonth()+getYear()+getDay()... but
i believe that there is a easiest way.
By the way, why the following line give NaN
new Date(datepickerBegin).getMonth()
but the following line works?
new Date(Date.parse(datepickerBegin.toString())).getMonth()

After parsing the dates using Date.parse(...);, you can use the Date constructor to create date types like so. An example of this process has been abstracted into the function below:
function parseDateAsDatePart(dateString) {
var parsedDate = new Date(Date.parse(dateString));
return new Date(parsedDate.getYear(), parsedDate.getMonth(), parsedDate.getDate());
}
Once you change both strings into Date objects, you may compare them as shown above.
Note: as Linus mentioned above, Date.parse(...) returns an integer, not a date object, so it needs to be wrapped in the Date constructor.

Try converting the dates to time, using the .getTime() method. If the dates are equal, they will have the same values returned from getTime. This assumes that you're only using string values for your dates (ie "9/6/12"). If your dates will have time stamps associated with them, then you'll need to use the setHours() function to set all the time reference to 0 (d.setHours(0,0,0,0);).
Links:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTime
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setHours
Example:
if(datePickerBegin.getTime() === datePickerEnd.getTime())
{
//...do something.
}
Note: If you do end up going the .getMonth() route, then be aware that the function returns the months as zero based numbers, so add 1 to what it returns.

You can try with getMonth, GetDays , ...
http://www.comptechdoc.org/independent/web/cgi/javamanual/javadate.html

Related

Javascript dates not shown as equal, despite getTime() function showing the dates ARE equal

I read somewhere that you can't compare Javascript dates using the date objects, but that you could using the getTime().
This is mostly working for me, except for one date. This is my code:
if (d1.getTime() != d2.getTime()) {
// Dates are not equal, new data present
Logger.log(d1); // Fri Jul 17 08:15:14 GMT+02:00 2015
Logger.log(d2); // Fri Jul 17 08:15:14 GMT+02:00 2015
}
To me, these look exactly equal.
The other 308 rows on the spreadsheet being parsed also show as equal.
== EDIT ==
Comparing the milliseconds of the date, they are in fact not equal. This is absurd, as if they are not equal, then the new date is inserted into CouchDB and that becomes the date to compare to on the next script run (without changing the date). So CouchDB in this case must be truncating milliseconds.
There can be difference in milli seconds. Check following example for reference:
var d1 = new Date();
var d2 = new Date();
d2.setMilliseconds(d2.getMilliseconds() + 2);
console.log(+d1, +d2);
console.log(d1, d2);
console.log(+d1 === +d2);
When you use getTime you are getting a millisecond timestamps. So they would only be equal if they refer to the same millisecond timestamp. If you are interested in comparing their String representation:
d1.toString() === d2.toString()
Edit: Sorry, had wrong formats before.

DatePicker Error in Angular JS due to UTC

I have selected the 12th of September 2014 in the UI.
Following is the code
ctrl.$formatters.push(function (modelValue) {
console.log(modelValue);
var dt = new Date(modelValue);
dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
console.log(dt)
return dt;
});
The two console logs i see are the following.
09/11/2014
Wed Sep 10 2014 18:30:00 GMT+0530 (IST)
Am not sure why the conversion from UTC to local is not carried out correctly.
Thanks in advance.
Its not clear what you are trying to do. The input does not have a time. Do you want to add the current time of the day to the arbitrary date? Or do you just want a local representation of the date? I'm geussing the latter.
Instead of dt.setMinutes(...) and the following two lines, replace all three lines with:
return dt.toLocaleDateString();
If you ARE trying to set the time to now on whatever date is input (I don't know why...) but you might try:
dt.setTime( new Date().getTime() );
instead of the setMinutes(...) line.
then you can
return dt.toLocaleString;
All date objects are stored as miliseconds since, like 1972. It is best to use the built in Date object methods to get what you want from it. Here are the docs for reference.

Prevent Javascript from creating dates with a large months

In Javascript if I create a date like so:
var y=new Date('2014','16','06')
Then y will be on my computer Wed May 06 2015 00:00:00 GMT-0400. However, the month I entered is 16 not 5. Is there anyway to prevent Javascript from creating a valid date in this instance (when Month is too big) and just return 'Invalid Date'?
Here's the relevant information from the Mozilla Javascript documentation for Date:
Note: Where Date is called as a constructor with more than one
argument, if values are greater than their logical range (e.g. 13 is
provided as the month value or 70 for the minute value), the adjacent
value will be adjusted. E.g. new Date(2013,13,1) is equivalent to new
Date(2014,1,1), both create a date for 2014-02-01 (note that the month
is 0-based). Similarly for other values: new Date(2013,2,1,0,70) is
equivalent to new Date(2013,2,1,1,10) which both create a date for
2013-03-01T01:10:00.
So in answer, no, that's the only behavior of the Date constructor, and any validation you want to do on your input values is going to have to be done by you before you pass them into the constructor.
However, one possible option could be to concatenate a string of your date value and then use Date.parse() on it, which will return a valid value if your date is correct or NaN if it isn't.

javascript date format using dateFormat String

I am working on Javascript dates, I have one date which is in the form of 20 Jun 13, I
need to convert it into a Date Object, I used Date.parse() which returns 1 June 2013.
var frmDt = '20 Jun 13';
alert(Date.parse(frmDt));
Which is the solution?
I found date handling in javascript made extremely easier by using momentJs, which allows you to construct moment objects that actually wrap native javascript Date objects in a very liberal way, passing in strings of many different formats and actually being able to get a date object, in a way that is way more reliable than Date.parse().
You can also pass in a date format string, so your case would be something like moment('20 Jun 13', 'DD MMM YY').
d3.js has very robust capabilities for parsing and formatting dates. See https://github.com/mbostock/d3/wiki/Time-Formatting.
I have taken the code posted in my comment and turned it into a function, made the jan,feb,mar case insensitie and the seperator character between day month year can be any character (as long is there is one). so any format dd mmm yy or dd/mmm/yy or d mmm yy will work:
function toDate(str){
var months={
"JAN":1,
"FEB":2,
//... other months
"JUN":6,
//... other months
"DEC":12
}
var r=/^(\d{1,2}).(\w{3}).(\d{2}$)/;
if(r.test(str)===false){
throw new Error("Invalid date string:"+str);
}
var replaceFunction=function(){
var years=parseInt(arguments[3],10);
var m=months[arguments[2].toUpperCase()];
if(typeof m==="undefined"){
throw new Error("Invalid month name:"+arguments[2]);
}
var days=arguments[1]
m=(m<9)?"0"+m:m;
days=(days.length===1)?days="0"+days:days;
years=(years>50)?years="19"+years:"20"+years;
return m+"/"+days+"/"+years;
};
return new Date(str.replace(r,replaceFunction));
}
console.log(toDate("20 Jun 13"));

How to use logic to perform operations only on date objects in an array in Google Apps Script

I am trying to build a script which will read a particular column in a spreadsheet, and only if the item in a particular cell is a date object (which Google scripts automatically renders from our format - MM/dd/yyyy) Google's date object gives all time parameters, as such:
Sat Apr 26 00:00:00 GMT-05:00 2014
I ONLY want the data stored from the column if it is a date object, so what logic would I put in an if() statement to accomplish this? I tried using regularexpressions, as follows
var dateFormat = new RegExp('[a-zA-Z]{3}\\s[a-zA-Z]{3}\\s[0-9]{2}\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\\sGMT-[0-9]{2}:[0-9]{2}\\s[0-9]{4}');
var line = "Thu Dec 31 00:00:00 GMT-06:00 2015";
Logger.log(dateFormat.test(line));
This test returns TRUE. So why does the logic not work directly on date objects?
And if you know about date objects in Apps scripts, where can I find information on operating on date objects. I am interested in detecting a date is 45 days in the future, 30 days in the future, and 15 days, and sending corresponding alerts for these dates coming up, then after 15 days sending an alert every day.
Your test does not work on Date objects because they are Date objects and not String objects.
use the instanceof operator (cellValue instanceof Date) to find out if it's a date.

Categories