This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Comparing dates
How to compare two dates in Objective-C
i want to compare 2 strings who have a date format "11-06-2011" and "12-06-2011" for exemple.
i want to see if the second date is greater than the first or not
can you help me please ?
i tried this code
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MM-YYYY"];
NSDate *date1 = [dateFormat dateFromString:deparatureDateField.text];
NSDate *date2 = [dateFormat dateFromString:comebackDateField.text];
[dateFormat release];
NSTimeInterval timeInterval = [date1 timeIntervalSinceDate:date2];
if(timeInterval >= 0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Attention" message:#"come back date should be greater" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alert show];
}
but i alwayse have an alert, NSTimeInterval timeInterval is alwayse NULL
To find out if one date is larger than the other you'd have to do this:
NSString *string1 = #"11-06-2011";
NSString *string2 = #"12-06-2011";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MM-yyyy"];
NSDate *date1 = [dateFormat dateFromString:string1];
NSDate *date2 = [dateFormat dateFromString:string2];
[dateFormat release];
NSComparisonResult comparisonResult = [date1 compare:date2];
/*
NSComparisonResult can be either of these values:
- NSOrderedAscending (-1) //if date1 < date2
- NSOrderedSame (0) //if date1 = date2
- NSOrderedDescending (1) //if date1 > date2
*/
Alternatively (to compare:) you could use timeIntervalSinceDate: to get the actual time difference:
NSTimeInterval timeInterval = [date1 timeIntervalSinceDate:date2];
//timeInterval will be
// - nagative if ascending,
// - zero if same,
// - positive if descending
Actually it depends what you will do after comparison. If you want to keep date info as a string and compare the strings is
[#"11-06-2011" isEqualToString: #"12-06-2011"]
is enough for you
look at NSDates timeIntervalSinceNow, you can compare the time interval from both dates to see which one is the most recent etc.
NSTimeInterval *interval = [someDate timeIntervalSinceNow];
Related
I have start date and end date in string format.i want to compare end date and start date,end date should be greater than start date.How to do this.
NSLog(#"%#",date);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd MM yyyy"];
_start_date = [[NSDate alloc] init];
_start_date = [df dateFromString: date];
NSLog(#"date: %#", _start_date);`
Getting nil on start_date.
You need to convert both the strings to NSDate objects using NSDateFormatter.
As your date is in dd-MM-yy format, do as shown below :
NSString *dateStr1 = #"21-3-14";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"dd-MM-yy"];
NSDate *date1 = [dateFormatter dateFromString:dateStr1];
Similarly create another date, say date2 Then you can compare these dates.
if ([date1 compare:date2] == NSOrderedDescending) {
NSLog(#"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
NSLog(#"date1 is earlier than date2");
} else {
NSLog(#"dates are the same");
}
Create an instance of NSDateFormatter.
Configure it.
Parse the strings to get NSDate objects (dateFromString:).
Compare them (compare:).
I have two NSString which have date i want that if they both have same data then if should work otherwise else should work
here is my code
NSString*test=data.addedDateTime;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy_MM_dd"];
NSDate* date = [NSDate date];
NSString* str = [formatter stringFromDate:date];
NSString*addedDateTime=str;
if ([test isEqualToString:str]) {
[todayArray addObject:theObject];
int count=[todayArray count];
NSLog(#"Today array working %d",count);
}
else {
[yesterdayArray addObject:theObject];
}
my code always runs else when there is same value in both i have checked using NSLog
Don't compare two NSStrings, which represent the dates, but compare two NSDates instead
First you convert string to date and use this [date1 isEqualToDate:date2].This is a compair a two date.
use this code I hope this code useful for you.
NSString*test=data.addedDateTime;
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy_MM_dd"];
NSDate* d = [df dateFromString:test];
[df release];
NSDate* date = [NSDate date];
if ([d isEqualToDate:date) {
[todayArray addObject:theObject];
int count=[todayArray count];
NSLog(#"Today array working %d",count);
}
else {
[yesterdayArray addObject:theObject];
}
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date1 = [dateFormatter dateFromString:TodatDate];
NSDateFormatter *dateFormatte = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatte setDateFormat:#"yyyy-MM-dd"];
NSDate *date2 = [dateFormatte dateFromString:ServerDate];
unsigned int unitFlags = NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:date1 toDate:date2 options:0];
int days = [comps day];
NSLog(#"%d",days);
Condition [test isEqualToString:str] always gives NO if date is either not equal or in not same formate. So dont use this.
Use NSDateComponent to compare two dates or Compare as #Andrey Gordeev
Says .
Try this code for any comparison between dates... You should not compare date in the form of string. Compare the dates before conversion to string. Convert the string "test" into date format using dateFromString function of the formatter by specifying the exact date format as that of the test. Then compare the dates using following function.
NSString*test=data.addedDateTime;
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"yyyy_MM_dd"];
NSDate *newDate = [formatter dateFromString:data.addedDateTime]; // other date
NSDate *today = [NSDate date]; // current date
NSComparisonResult result;
result = [today compare:newDate]; // comparing two dates
if(result == NSOrderedSame)
{
[todayArray addObject:theObject];
int count=[todayArray count];
NSLog(#"Today array working %d",count);
}
else
{
[yesterdayArray addObject:theObject];
}
Instead of comparing String compare Date. Like this,
NSDate *myDate1 =data.addedDateTime;
NSDate* mydate2 = [NSDate date];
if ([myDate1 compare:mydate2] == NSOrderedDescending) {
NSLog(#"Dilip myDate1 is later than myDate2");
} else if ([myDate1 compare:mydate2] == NSOrderedAscending) {
NSLog(#"Dilip myDate1 is earlier than myDate2");
} else {
NSLog(#"Dilip dates are the same");
}
first u should convert date to nsstring..
then u set perfect date formate in both string..
like
NSDate *today1 = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MM-yyyy"];
NSString *dateString11 = [dateFormat stringFromDate:today1];
[dateString11 retain];
ur first string is like dateString11
and other date string is like str2=#"03-10-2010";
then u compare two string
if ([dateString11 isEqualToString:str2]) {
[todayArray addObject:theObject];
int count=[todayArray count];
NSLog(#"Today array working %d",count);
}
This question already has answers here:
How to make another array containing number of days remain
(3 answers)
Closed 9 years ago.
i have one array something like below
_combinedBirthdates(
"03/12/2013",
"03/12/2013",
"08/13/1990",
"12/09/1989",
"02/06",
"09/08",
"03/02/1990",
"08/22/1989",
"03/02",
"05/13",
"10/16",
"07/08",
"08/31/1990",
"04/14/1992",
"12/15/1905",
"08/14/1989",
"10/07/1987",
"07/25",
"07/17/1989",
"03/24/1987",
"07/28/1988",
"01/21/1990",
"10/13"
)
this all are NSString
i am trying to make new array from this which contains days remaining something like below
(days remaining for particular birthdate)
(we will compair current date with above date array and we will find out remaining days)
_newarray(
"125",
"100",
"65",
and till end like this..
)
i am using below code for this
unsigned int unitFlags = NSDayCalendarUnit;
NSCalendar *currCalendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSLog(#" currCalendar%#",currCalendar);
NSMutableArray * _newarray = [[NSMutableArray alloc] init];
for (NSString * str in _combinedBirthdates){
NSDate * toDate = [dateFormatter dateFromString:str];
NSDateComponents *daysInfo = [currCalendar components:unitFlags fromDate:[NSDate date] toDate:toDate options:0];
int days = [daysInfo day];
[_newarray addObject:[NSString stringWithFormat:#"%d",days]];
}
NSLog(#" _newarray%#",_newarray);
and this is what i am getting as output when i print _newarray plz help me thank you
_newlymadeArray(
"-1",
"-1",
"-8248",
"-8495",
"-4454",
"-4454",
"-8412",
"-8604",
"-4454",
"-4454",
"-4454",
"-4454",
"-8230",
"-7638",
"-39170",
"-8612",
"-9289",
"-4454",
"-8640",
"-9486",
"-8994",
"-8452",
"-4454",
"-2072",
"-888",
"-8315"
)
Please try to use this.I think this one may help you.
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:#"dd/MM/yyyy"];
NSString *str = [tempFormatter stringFromDate:#"yourStartDate"];
NSDate *startdate = [tempFormatter dateFromString:str];
str = [tempFormatter stringFromDate:#"yourEndDate"];
NSDate *endDate = [tempFormatter dateFromString:str];
int i = [startdate timeIntervalSince1970];
int j = [toDate timeIntervalSince1970];
double X = j-i;
int days=(int)((double)X/(3600.0*24.00));
use below code to compare two dates pass both date in same format
NSDateFormatter *dateformat = [[NSDateFormatter alloc]init];
[dateformat setDateFormat:#"dd/MM/yyyy"];
NSString *StrDate1 = [dateformat stringFromDate:[NSDate date]];
NSString *StrDate2 = [dateformat stringFromDate:date2];
NSDate *firstDate = [dateformat dateFromString:StrDate1];
NSDate *secondDate = [dateformat dateFromString:StrDate2];
NSTimeInterval lastDiff = [firstDate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [secondDate timeIntervalSinceNow];
NSTimeInterval dateDiff = todaysDiff - lastDiff;
int day = dateDiff/(3600*24);
// days are remaining
use this in for loop you will gate remaining days
Need to compare two variables of type NSDate.
One is the current date and the other is user selected date.
The user selects the date :
UIDatePicker *datePicker; // declared in h file
-(void)dateChange:(id)sender{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd-MM-yyy"];
dateLabel.text = [NSString stringWithFormat:#"%#", [df stringFromDate:datePicker.date]];
userDebtInfo.duration = dateLabel.text;}
Validation Method :
-(IBAction) validation:(id)sender{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSString *dateString = [dateFormat stringFromDate:today];
[dateFormat release];
if ((userDebtInfo.debt_code == userTmp.debt_code) && ([userDebtInfo.duration compare:dateString]== NSOrderedDescending)))
[bl updateUserMoneyValidation:userDebtInfo];
else
[bl saveUserMoneyValidation:userDebtInfo];}
I have tested and is comparing two strings. Can someone help me with some advice about this condition, please?
I want to compare if the selected date is after the current date to do insert or update the database.
Thank you!
You could use NSDate compare function
if([firstDate compare:secondUpdate] == NSOrderedAscending){
//This will return YES if secondUpdate is the recent date between the two dates
}
NSOrderedAscending is a constant of NSComparisonResult
Here are the other constants you could compare to:
enum {
NSOrderedAscending = -1,
NSOrderedSame,
NSOrderedDescending
};
typedef NSInteger NSComparisonResult;
If you already have two objects of type NSDate, you could use one of the NSDate comparison methods. For instance [NSDate compare:] which returns a NSComparisonResult (this is the same enum as returned by [NSString compare:]).
I have two times :
10:23:51
10:31:54
Both values are stored as strings in a SQLite database.
I want to find the difference between these two times in hh:mm format.
How can I do this?
I have searched a lot. But can't find a proper solution.
Help me out.
Thanks.
Edit :
See basically I am having two arrays:
InTimeArray and OuttimeArray.
Now in the viewDidload method , I am fetching all the intime entries in the IntimeArray and Outtime entries in the outtime Arrays.
Now I am passing one by one values in tableview like in 1st row
IntimeArray[0]
OuyTimeArray[0]
second row:
IntimeArray[1]
OuyTimeArray[1]
Now I want to count the differences between 1st row's intime and outtime in HH:MM format.
I am really confused.
you can take a look at that :
-(NSDate *)dateFromString:(NSString *)string
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormat setLocale:locale];
[dateFormat setDateFormat:#"HH:mm:ss"];
NSDate *date1 = [dateFormat dateFromString:string];
if(!date1) date1= [NSDate date];
[dateFormat release];
[locale release];
return date1;
}
this will turn the NSDate to you and when you change them both to NSDates then you can learn the difference by looking at this.
i hope this will help you..
You have to first change your both strings into date format using this method :-
- (NSDate *)dateFromString:(NSString *)string;
after that you just have to calculate number of seconds between both the dates.Thats it.
OR there is another simple way to do this. i.e.
get dates from both arrays first like this:-
NSDate *eventStartDate = [IntimeArray objectAtIndex:indexpath.row];
NSDate *eventEndDate = [OuyTimeArray objectAtIndex:indexpath.row];
Then calculate difference between both the dates like this :-
NSTimeInterval startTimeInterval = [eventStartDate timeIntervalSinceDate:currentDate];
Hope it helps Thanks :)
Try this:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *d1 = [formatter dateFromString:IntimeArray[0]];
NSDate *d2 = [formatter dateFromString:OuyTimeArray[0]];
NSTimeInterval ti = [d2 timeIntervalSinceDate:d1];
float hours = floor(ti / 3600);
float minutes = floor((ti - hours*3600) / 60);
NSString *s = [NSString stringWithFormat:#"%02.0f:%02.0f",hours,minutes];
For your given example, NSLog(#"Time passed: %#",s); will print 00:08.