I have a script that is comparing two dates against each other. But both are coming in differently. one I converted to a string format Mo/day/year then to a date format. The other is taken directly for a google spreadsheet cell already in date format. But when I run a comparison on them, it doesn't work even if the date falls within the comparison range. Here's my code:
function formatDate(someDate){
var x = someDate.split("T");
var v = x[0].split("-");
var newDate = new Date();
newDate.setFullYear(v[0],(v[1]-1),v[2]);
//var newDate = v[1]+"/"+ v[2]+"/"+v[0];
return newDate;
}
//calling formatDate within another function
if(startDate != ''){
if(singleCard[j].date != undefined){
var k = singleCard[j].date;
var f = formatDate(k);
var dt = new Date(f);
if(dt >= startDate && dt <= endDate){ //date comparison
//do something here
}
The start/end dates is coming in a format of:
Fri Oct 12 2012 00:00:00 GMT-0700 (PDT)
The singleCard[j].date is coming in as a string:
"2012-10-12T16:57:51.517Z"
and then I use:
var f = formatDate(date) -> var dt = new Date(f)
to process it.
I'm not sure what I'm doing wrong here. Thanks.
When you do
var newDate = v[1]+"/"+ v[2]+"/"+v[0];
are you sure you used year / month / day in the right order ?
Did you try to log the result of var dt = new Date(f);
to see its value as a date object ?
sorry if my questions seem obvious but since I don't know your local settings for date I can't be sure how you handle that.( I'm in a country where we use dd/mm/yyyy so I'm used to have problems with that ;)
EDIT : just saw your comment... shouldn't it be v[0]+"/"+ v[1]+"/"+v[2]
(yyyy/mm/dd)
EDIT 2 : I think you have to give hh mm ss parameters as well when you use setFullYear();
something like
newDate.setFullYear(v[0],(v[1]-1),v[2],0,0,0,0);
in order to get it working. It is also necessary (I'd even say mandatory) to set hh mm ss and mSec to 0 since you are using a <=
and >=
comparison, Equality will probably never be true if you let hours , minutes , seconds and milliseconds free to live their own life.
Don't forget date objects are ALWAYS complete dates with time, even when you don't show / use them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.