I have implemented two textFields From and To in ViewController.When the user selects the textField he is able to select the date from the calendar. The selected Date is stored in the TextField as
YYYY-MM-dd format.
And I have implemented a calculate button in ViewController.When the Two TextField are filled i need to do some work.
When the two textField are filled and the From TextField is greater , I want to display an alert when the From TextField date is Greater than To TextField.
How can i Compare it...?
Perfect solution
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *textFieldDateString1 = #"2016-07-14";
NSString *textFieldDateString2 = #"2016-07-15";
NSDate *date1 = [dateFormatter dateFromString:textFieldDateString1];
NSDate *date2 = [dateFormatter dateFromString:textFieldDateString2];
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");
}
Printed Result is
date1 is earlier than date2
Date Comparision
Compare Two dates
NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat: #"yyyy-MM-dd"];
NSDate * dt1 ;
NSDate * dt2 ;
dt1 = [df dateFromString: txt1.text];
dt2 = [df dateFromString: txt2.text];
NSComparisonResult result = [dt1 compare: dt2];
switch (result) {
case NSOrderedAscending:
NSLog(#"%# is greater than %#", dt2, dt1);
break;
case NSOrderedDescending:
NSLog(#"%# is less %#", dt2, dt1);
break;
case NSOrderedSame:
NSLog(#"%# is equal to %#", dt2, dt1);
break;
default:
NSLog(#"erorr dates %#, %#", dt2, dt1);
break;
}
Hope this will help you....
i think you are looking for this functionality..
NSCalendar* currentCalendar = [NSCalendar currentCalendar];
NSCalendarUnit unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;
NSDateComponents *differenceComponents = [currentCalendar components:unitFlags fromDate:postdate toDate:[NSDate date] options:0];
NSInteger yearDifference = [differenceComponents year];
NSInteger monthDifference = [differenceComponents month];
NSInteger dayDifference = [differenceComponents day];
NSInteger hourDifference = [differenceComponents hour];
NSInteger minuteDifference = [differenceComponents minute];
i hope this will help you..
First you have to convert this two text field string date into NSDate object and and use compare: method of date to compare date.
NSString *dateString1 = #"2016-05-31"; //First text field value
NSString *dateString2 = #"2016-05-31"; //Second text field value
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:#"YYYY-MM-dd"];
NSDate *date1=[dateFormatter dateFromString:dateString1];
NSDate *date2=[dateFormatter dateFromString:dateString2];
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");
}
Related
How to check the date cross the Sunday and reset the data?
I need to do reset on every Sunday, if I missed that on Sunday then the reset need to happen if user open the app the following increment date(i.e mon,tue, till saturday).
For Every Sunday or crossed the Sunday one time the reset need to happened, if user forgot to open the application on Rest date.
Following the my code which i try to implemented.
Which was not working as per my requirement, Your feedback is highly appreciated.
-(void) weekDaySundayToRefresh
{
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekday fromDate:now];
NSUInteger weekdayToday = [components weekday];
NSInteger daysToMonday = (8 - weekdayToday) % 7;
nextSunday= [now dateByAddingTimeInterval:60*60*24*daysToSunday];
NSLog(#"nextMonday : %#", nextSunday);
}
-(void) compareDate
{
NSDate *today = [NSDate date]; // it will give you current date
// NSDate *newDate = [MH_USERDEFAULTS objectForKey:#"USER_BACKGROUND_DATE"]; // your date
NSComparisonResult result;
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
result = [today compare:refreshGoalsDate]; // comparing two dates
if(result==NSOrderedAscending)
{
NSLog(#"today is less");
}
else if(result==NSOrderedDescending)
{
NSLog(#"newDate is less");
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&fromDate
interval:NULL forDate:refreshGoalsDate];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&toDate
interval:NULL forDate:today];
NSDateComponents *difference = [calendar components:NSCalendarUnitDay
fromDate:fromDate toDate:toDate options:0];
noOfDaysCount = [difference day];
NSLog(#"date difference:%ld",(long)[difference day]);
}
else
NSLog(#"Both dates are same");
}
-(void) checkRefreshGoals:(int)sectionIndex rowIndex:(int)rowIndex
{
NSDateFormatter * formatter = [NSDateFormatter new];
[formatter setDateFormat:#"yyyy-MM-dd"];
NSString * currentDateString = [formatter stringFromDate:[NSDate date]];
NSString * initialNotificationDate = [formatter stringFromDate:refreshDate];
NSDate *currentDate = [formatter dateFromString:currentDateString];
NSDate *refreshDate = [formatter dateFromString:initialNotificationDate];
if ([refreshDate compare:currentDate] == NSOrderedDescending)
{
NSLog(#"date1 is later than date2");
isGoalsRefreshed = NO;
}
else if ([refreshDate compare:currentDate] == NSOrderedAscending)
{
NSLog(#"date1 is earlier than date2");
if (sameDay == YES)
{
isGoalsRefreshed = YES;
[self refreshDataOnSunday:sectionIndex rowIndex:rowIndex];
}
else if (noOfDaysCount > 7)
{
isGoalsRefreshed = YES;
[self refreshDataOnSunday:sectionIndex rowIndex:rowIndex];
}
else
{
isGoalsRefreshed = NO;
}
}
else
{
NSLog(#"dates are the same");
isRefreshed = NO;
}
}
-(void) refreshDataOnSunday:(int)sectionIndex rowIndex:(int)rowIndex
{
if (noOfDaysCount > 7)
{
if (isGoalsRefreshed == YES)
{
// Do rest your data
}
}
else if (sameDay == YES)
{
if (isGoalsRefreshed == YES)
{
// Do reset your data
}
}
else
{
isGoalsRefreshed = NO;
}
}
First you need to save todays date and DayNumber when user opens your app at first time and then you need to compare next app open date so you can estimate either Sunday is gone or not.
/*first check in userDefault for stored Date and Day
Store values in local and check with current date */
NSMutableDictionary *dictStoredData = [USERDEFAULT valueForKey:#"dateTimeDate"];
if (!dictStoredData) {
// user comes first time so store it here
dictStoredData =[[NSMutableDictionary alloc] init];
NSDate *today =[NSDate date];
NSCalendar *gregorian =[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps =[gregorian components:NSCalendarUnitWeekday fromDate:[NSDate date]];
NSInteger weekday = [comps weekday];
int nextSundayVal = 7 - (int)weekday;
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd"];
NSString *startDate = [format stringFromDate: today];
[dictStoredData setObject:startDate forKey:#"startDate"];
[dictStoredData setObject:[NSString stringWithFormat:#"%d",nextSundayVal] forKey:#"nextSundayVal"];
[USERDEFAULT setObject:dictStoredData forKey:#"dateTimeDate"];
}
else{
NSString *strEndDate = #"2017-01-08";
NSString *strStartDate = [dictStoredData valueForKey:#"startDate"];
int nextSundayVal = (int)[dictStoredData valueForKey:#"nextSundayVal"];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd"];
NSDate *startDate = [format dateFromString:strStartDate];
NSDate *endDate = [format dateFromString:strEndDate];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
fromDate:startDate
toDate:endDate
options:0];
int newDayCount = (int)[components day];
if (newDayCount > nextSundayVal) {
NSLog(#"sunday is gone so reload data!!");
//save this date as a new date and check with this when user come again
}
else {
NSLog(#"sunday is not come yet!!");
}
}
here strEndDate is next date when user opens your application so you can get it from [NSDate date] with same dateformater.
I have run this code in my machine and its printing sunday is gone so reload data so hope this will help you.
As like you we had flow, every friday and more than seven days, its need to update the server.
We did it with following code:
You need to update last updated date.
Check this out:
if ([isFirday isEqualToString:#"Friday"]) {//This is my value from server side (they will give as friay), i think you dont need this condition.
BOOL isSameDay;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM dd yyyy,HH:mm"];
NSDate *date = [dateFormatter dateFromString:mennuRefreshTime];//Is an last updated date.
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *temp = [dateFormatter stringFromDate:date];
NSDate *lastDate = [dateFormatter dateFromString:temp];
NSString *currentDaystr = [dateFormatter stringFromDate:[NSDate date]];
// Write the date back out using the same format
NSDate *currentDate = [dateFormatter dateFromString:currentDaystr];
if ([lastDate compare:currentDate] == NSOrderedDescending) {
NSLog(#"date1 is later than date2");
isSameDay = NO;
} else if ([lastDate compare:currentDate] == NSOrderedAscending) {
NSLog(#"date1 is earlier than date2");
[dateFormatter setDateFormat:#"EEEE"];
NSString *dayName = [dateFormatter stringFromDate:currentDate];
NSString *lastupdateName = [dateFormatter stringFromDate:lastDate];
if ([dayName isEqualToString:lastupdateName]) {
isSameDay = YES;
}else{
isSameDay = NO;
}
} else {
NSLog(#"dates are the same");
isSameDay = YES;
}
if (isSameDay == YES) {
return;
}
NSCalendar *calender =[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calender components:NSCalendarUnitDay fromDate:lastDate toDate:currentDate options:0];
int day = (int)[components day];
if (day >= 7) {
[self getTopList];
}else{
[dateFormatter setDateFormat:#"EEEE"];
NSString *dayName = [dateFormatter stringFromDate:currentDate];
if ([dayName isEqualToString:isFirday]) {
[self getTopList];
}else{
return;
}
}
}
I am working on chat apps and I want to send date/time in particular format like Today, yesterday with date. How can I display according to this format?
- (NSString *)relativeDateStringForDate:(NSDate *)date
{
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitWeekOfYear |
NSCalendarUnitMonth | NSCalendarUnitYear;
NSDateComponents *components = [[NSCalendar currentCalendar] components:units
fromDate:date
toDate:[NSDate date]
options:0];
if (components.year > 0) {
return [NSString stringWithFormat:#"%ld years ago", (long)components.year];
} else if (components.month > 0) {
return [NSString stringWithFormat:#"%ld months ago", (long)components.month];
} else if (components.weekOfYear > 0) {
return [NSString stringWithFormat:#"%ld weeks ago", (long)components.weekOfYear];
} else if (components.day > 0) {
if (components.day > 1) {
return [NSString stringWithFormat:#"%ld days ago", (long)components.day];
} else {
return #"Yesterday";
}
} else
{
return #"Today";
}
}
I am using above function to get date but I want date time in combined string. So how to pass date/time combine to the above method? Is it possible to send a date time string to this method?
For getting the date in format [08-jan-17 11:20:51], you can use the below code
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// Convert to new Date Format
[dateFormatter setDateFormat:#"dd-MMM-yy HH:mm:ss"];
NSDate *date = [NSDate date];
NSString *newDate = [dateFormatter stringFromDate:date]
NSLog(#"[%#]",newDate); // this will give you the date in format [08-jan-17 11:20:51]
For getting the time in format [10:01:20], you can use the below code
// Convert to new Time Format
[dateFormatter setDateFormat:#"HH:mm:ss"];
NSDate *date = [NSDate date];
NSString *newTime = [dateFormatter stringFromDate:date];
NSLog(#"%#",newTime); // this will give you the time in format 10:01:20
So you can use your code like this -
- (NSString *)relativeDateStringForDate:(NSDate *)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// Convert to new Date Format
[dateFormatter setDateFormat:#"dd-MMM-yy HH:mm:ss"];
NSString *newDate = [dateFormatter stringFromDate:date];
NSLog(#"[%#]",newDate);
// Convert to new Time Format
[dateFormatter setDateFormat:#"HH:mm:ss"];
NSString *newTime = [dateFormatter stringFromDate:date];
NSLog(#"%#",newTime);
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitWeekOfYear |
NSCalendarUnitMonth | NSCalendarUnitYear;
NSDateComponents *components = [[NSCalendar currentCalendar] components:units
fromDate:date
toDate:[NSDate date]
options:0];
if (components.year > 0) {
return [NSString stringWithFormat:#"[%ld years ago], [%#]", (long)components.year, newDate];
} else if (components.month > 0) {
return [NSString stringWithFormat:#"[%ld months ago], [%#]", (long)components.month, newDate];
} else if (components.weekOfYear > 0) {
return [NSString stringWithFormat:#"[%ld weeks ago], [%#]", (long)components.weekOfYear, newDate];
} else if (components.day > 0) {
if (components.day > 1) {
return [NSString stringWithFormat:#"[%ld days ago], [%#]", (long)components.day, newDate];
} else {
return [NSString stringWithFormat:#"[Yesterday %#]",newTime];
}
} else
{
return [NSString stringWithFormat:#"[Today %#]", newTime];
}
}
A couple of observations:
You want NSCalendarUnitWeekOfMonth, not NSCalendarUnitWeekOfYear.
In order to distinguish between "today" and "yesterday", you can't just get the date components between two NSDate objects. You should get the date components (but not time components) of the two dates first, and then get the difference between those two sets of date components.
As it is, if it's 9am and you're looking at a message from 11pm last night, it will calculate that day < 1, and thus it will say "Today 11pm" (which is wrong) rather than "Yesterday 11pm".
If you're going to include that "x months ago" string, I'd suggest getting out of the business of building it yourself. Apple has a class that does that for you (NSDateComponentsFormatter) and it's localized.
So, pulling that all together, you get something like:
- (NSString *)relativeDateStringForDate:(NSDate *)date {
// get the number of days differences
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitWeekOfMonth | NSCalendarUnitMonth | NSCalendarUnitYear;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:units fromDate:date];
NSDateComponents *nowComponents2 = [calendar components:units fromDate:[NSDate date]];
NSDateComponents *components = [calendar components:units fromDateComponents:dateComponents toDateComponents:nowComponents2 options:0];
if (components.year > 0 || components.month > 0 || components.weekOfMonth > 0 || components.day > 1) {
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = units;
formatter.maximumUnitCount = 2; // set this to whatever you want, but 1 or 2 is often best
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
return [NSString stringWithFormat:#"%# %#", [formatter stringFromDateComponents:components], NSLocalizedString(#"ago", #"x days _ago_")];
} else {
// build time string
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeStyle = NSDateFormatterShortStyle;
NSString *timeString = [formatter stringFromDate:date];
if (components.day == 1) {
return [NSString stringWithFormat:#"%# %#", NSLocalizedString(#"Yesterday", #"day before today"), timeString];
} else {
return [NSString stringWithFormat:#"%# %#", NSLocalizedString(#"Today", #"well, er, today"), timeString];
}
}
}
Now, notice that I excluded the time if the date was before yesterday. The time doesn't make sense if the date string is measured in any units greater than days (e.g. the time is meaningless in this string: "3 months ago, 11:20am"). If you want to include the time, you have to include the date (which then renders these relative "ago" strings useless). So you might just get rid of this "ago" portion:
- (NSString *)relativeDateStringForDate:(NSDate *)date {
// get the number of days differences
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitWeekOfMonth | NSCalendarUnitMonth | NSCalendarUnitYear;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:units fromDate:date];
NSDateComponents *nowComponents2 = [calendar components:units fromDate:[NSDate date]];
NSDateComponents *components = [calendar components: NSCalendarUnitDay fromDateComponents:dateComponents toDateComponents:nowComponents2 options:0];
if (components.day > 1) {
// build date/time string
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeStyle = NSDateFormatterShortStyle;
formatter.dateStyle = NSDateFormatterShortStyle;
return [formatter stringFromDate:date];
} else {
// build time string
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeStyle = NSDateFormatterShortStyle;
NSString *timeString = [formatter stringFromDate:date];
if (components.day == 1) {
return [NSString stringWithFormat:#"%#, %#", NSLocalizedString(#"Yesterday", #"day before today"), timeString];
} else {
return [NSString stringWithFormat:#"%#, %#", NSLocalizedString(#"Today", #"well, er, today"), timeString];
}
}
}
That solves the weird "3 months ago, 11:20am" problem, but then again, it's no longer a relative date/time string.
Another option is to abandon absolute time altogether, and just show a relative string:
- (NSString *)relativeDateStringForDate:(NSDate *)date {
NSCalendarUnit units = NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitWeekOfMonth | NSCalendarUnitMonth | NSCalendarUnitYear;
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = units;
formatter.maximumUnitCount = 2;
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
return [NSString stringWithFormat:#"%# %#", [formatter stringFromDate:date toDate:[NSDate date]], NSLocalizedString(#"ago", #"x days _ago_")];
}
The details of the above samples is less important than the basic concepts, namely:
Be careful using date components when determining "today" vs "yesterday";
Use date formatters when trying to create the time strings or date/time strings; and
Use date components formatters when trying to build a string that represents the amount of time (or days) that has elapsed.
I'd like to compare two different times in an if statement. Fort example
if (10:37 > 09:00) // DO SOMETHING
Is there a way to do this using NSDate and NSDateFormatter?
NSDate *date1;
NSDate *date2;
if([date1 laterDate:date2] == *it will return the later date, either date1 or date2*)
Try this
//Date formatter - to format the sample dates using for comparison
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateFormat:#"HH:MM:SS"];
// Creating 2 sample dates
NSDate *date1 = [dateformatter dateFromString:#"10:10:10"];
NSDate *date2 = [dateformatter dateFromString:#"10:10:20"];
if (NSOrderedDescending == [date1 compare:date2])// Here comparing the dates
{
NSLog(#"date1 later than date 2");
}
else
{
NSLog(#"date2 later than date 1");
}
You need to use timeIntervalSinceDate api for comparing two different times.
As I understand your question, you only have times, not dates. Actually than NSDate isn't the best choice, as it represents exactly one moment in time for all eternity.
If you only have times or recurring dates, NSDateComponents are the better choice. You can define what components is used, in your case hour and minute.
NSDateComponents have one caveat: no compare: method, but you can easily compare as
if (date1Comps.hour < date2Comps.hour) {
NSLog(#"date 1 earlier");
} else if(date1Comps.hour > date2Comps.hour) {
NSLog(#"date 2 earlier");
} else {
if (date1Comps.minute < date2Comps.minute) {
NSLog(#"date 1 earlier");
} else if(date1Comps.minute > date2Comps.minute){
NSLog(#"date 2 earlier");
} else {
NSLog(#"same hour, same minute");
}
}
here is the full code including creating components from dates.
NSString *date1String = #"2014-07-18T10:30";
NSString *date2String = #"2014-07-18T10:45";
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd'T'HH:mm"];
NSDate *date1 = [f dateFromString:date1String];
NSDate *date2 = [f dateFromString:date2String];
NSDateComponents *date1Comps = [[NSCalendar currentCalendar] components:(NSCalendarUnitHour|NSCalendarUnitMinute) fromDate:date1];
NSDateComponents *date2Comps = [[NSCalendar currentCalendar] components:(NSCalendarUnitHour|NSCalendarUnitMinute) fromDate:date2];
if (date1Comps.hour < date2Comps.hour) {
NSLog(#"date 1 earlier");
} else if(date1Comps.hour > date2Comps.hour) {
NSLog(#"date 2 earlier");
} else {
if (date1Comps.minute < date2Comps.minute) {
NSLog(#"date 1 earlier");
} else if(date1Comps.minute > date2Comps.minute){
NSLog(#"date 2 earlier");
} else {
NSLog(#"same hour, same minute");
}
}
or similar: order the date components in an array
NSArray *times = [#[date1Comps, date2Comps] sortedArrayUsingComparator:^NSComparisonResult(NSDateComponents *date1Comps, NSDateComponents *date2Comps) {
if (date1Comps.hour < date2Comps.hour) {
return NSOrderedAscending;
} else if(date1Comps.hour > date2Comps.hour) {
return NSOrderedDescending;
} else {
if (date1Comps.minute < date2Comps.minute) {
return NSOrderedAscending;
} else if(date1Comps.minute > date2Comps.minute){
return NSOrderedDescending;
}
}
return NSOrderedSame;
}];
You can save this comparison block and reuse it. Than it won't matter much that there is no easy compare method.
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger todayHour = [components hour];
NSInteger currentMinute = [components minute];
if (currentHour < 7 || (currentHour > 21 || currentHour == 21 && (currentMinute > 0 || currentMinute > 0))) {
// Do your task
}
This may helps you :)
I'm getting the date string from server in 01/02/2014 16:43:00 AM format, which is having GMT timeZone.
I've to compare that date with current date for live streaming. If the current date is lesser than that server date I've to show some alert which shows the correct live starting time. But I'm not able to compare them.
How to convert that server date string to date format and how to compare that date with current date ?
I'm using the following code :
NSString *DateFromServer = video.Eventutcstart;
NSDateFormatter * dateFormatter1 = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSString *tzName = [timeZone name];
[dateFormatter1 setTimeZone:[NSTimeZone timeZoneWithName:tzName]];
[dateFormatter1 setDateFormat:#"MM/dd/yyyy HH:mm:ss a"];
NSString *str = [dateFormatter1 stringFromDate:[NSDate date]];
NSDate *currentDate = [dateFormatter1 dateFromString:str];
NSDate *serverDate = [dateFormatter1 dateFromString: DateFromServer];
NSLog(#"currentDate %#", currentDate);
NSLog(#"serverDate %#", serverDate);
NSComparisonResult result;
result = [currentDate compare:serverDate];
if(result == NSOrderedDescending)
{
NSLog(#"alert message");
}
output:
2014-01-03 11:30:25.346 VMS[955:70b] currentDate 2014-01-02 19:00:23 +0000
2014-01-03 11:30:32.088 VMS[955:70b] serverDate 2014-01-02 19:00:46 +0000
Please help me to solve this....
Please use below code. You were not setting timezone correctly:
NSString *DateFromServer = video.Eventutcstart;
NSDateFormatter * dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter1 setDateFormat:#"MM/dd/yyyy HH:mm:ss a"];
NSString *str = [dateFormatter1 stringFromDate:[NSDate date]];
NSDate *currentDate = [dateFormatter1 dateFromString:str];
NSDate *serverDate = [dateFormatter1 dateFromString: DateFromServer];
NSLog(#"currentDate %#", currentDate);
NSLog(#"serverDate %#", serverDate);
NSComparisonResult result;
result = [currentDate compare:serverDate];
if(result == NSOrderedDescending)
{
NSLog(#"alert message");
}
For date comparison only,
You have two dates correctly obtained so can use :
int days1 = [currentDate timeIntervalSince1970] / 86400;
int days2 = [serverDate timeIntervalSince1970] / 86400;
if(days1==days2)
{
//do something;
}
else
{
//do something
}
Above code does not takes time in consideration and compares only year/month/day
For NSdate time comparison
unsigned int flags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* component1 = [calendar components:flags fromDate:currentDate];
NSDateComponents* component2 = [calendar components:flags fromDate:serverDate];
NSDate* currentDateTimeOnly = [calendar dateFromComponents:component1];
NSDate* serverDateTimeOnly = [calendar dateFromComponents:component2];
NSComparisonResult result;
result = [currentDateTimeOnly compare:serverDateTimeOnly];
if(result == NSOrderedDescending)
{
NSLog(#"alert message");
}
try this code
if(result == NSOrderedAscending)
{
NSLog(#"alert message");
}
instead of this one
if(result == NSOrderedDescending)
{
NSLog(#"alert message");
}
if you want to check both constraint with both date then you can use bellow code.
if(result == NSOrderedAscending){
NSLog(#"serverDate is in the future");
}else if(result == NSOrderedDescending){
NSLog(#"serverDate is in the past");
}else{
NSLog(#"Both dates are the same");
}
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSUserDefaults *def=[NSUserDefaults standardUserDefaults];
NSString *a1=[def objectForKey:#"Currentdate"];
NSDate *now = [dateFormat dateFromString:a1];
NSDate * currentdate = [NSDate date];
NSString *nowstr=[dateFormat stringFromDate:currentdate];
NSDate *todaydate=[dateFormat dateFromString:nowstr];
NSLog(#"Now is %# and current date is %#",[def objectForKey:#"Currentdate"],nowstr);
NSComparisonResult result = [todaydate compare:now];
switch (result)
{
case NSOrderedAscending:
dateiswhich=-1;
NSLog(#"%# is in future from %#", currentdate, now);
break;
case NSOrderedDescending:
dateiswhich=1;
NSLog(#"%# is in past from %#", currentdate, now);
break;
case NSOrderedSame: dateiswhich=-1;
break;
default: NSLog(#"erorr dates %#, %#", currentdate, now); break;
}
use above code might be useful to you
This question already has answers here:
How to compare two NSDates: Which is more recent?
(13 answers)
Closed 9 years ago.
I got to two date string in 24 Hours format how to compare ? For example
The current date :2013-06-27 13:51
The server date :2013-06-27 11:51
The current date cannot greater than the server date.Please help
Here is the datepicker
NSDateFormatter *datePickerFormat = [[NSDateFormatter alloc] init];
[datePickerFormat setDateFormat:#"yyyy-MM-dd HH:mm"];
self.myCurrentDate = [datePickerFormat stringFromDate:self.myDatePicker.date];
NSDate *myDate = [datePickerFormat dateFromString:self.myCurrentDate];
I not able to convert it to 24 hours format, and final datetime show is incorrect.
Try this,
// The current date :2013-06-27 13:51
// The server date :2013-06-27 11:51
NSString *strCurrentDate = #"2013-06-27 13:51";
NSString *strServerDate =#"2013-06-27 11:51";
NSDateFormatter *datePickerFormat = [[NSDateFormatter alloc] init];
[datePickerFormat setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *currentDate = [datePickerFormat dateFromString:strCurrentDate];
NSDate *serverDate = [datePickerFormat dateFromString:strServerDate];
NSLog(#"date %#",currentDate);
NSLog(#"date %#",serverDate);
NSComparisonResult result;
result = [currentDate compare:serverDate]; // comparing two dates
if(result == NSOrderedAscending)
NSLog(#"current date is less");
else if(result == NSOrderedDescending)
NSLog(#"server date is less");
else if(result == NSOrderedSame)
NSLog(#"Both dates are same");
else
NSLog(#"Date cannot be compared");
Try this class utility:
.h
#import <Foundation/Foundation.h>
#interface NSDate (Compare)
-(BOOL) isLaterThanOrEqualTo:(NSDate*)date;
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date;
-(BOOL) isLaterThan:(NSDate*)date;
-(BOOL) isEarlierThan:(NSDate*)date;
#end
.m
#import "NSDate+Compare.h"
#implementation NSDate (Compare)
-(BOOL) isLaterThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedAscending);
}
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedDescending);
}
-(BOOL) isLaterThan:(NSDate*)date {
return ([self compare:date] == NSOrderedDescending);
}
-(BOOL) isEarlierThan:(NSDate*)date {
return ([self compare:date] == NSOrderedAscending);
}
#end
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 self.serverDate into date format using dateFromString function of the formatter by specifying the exact date format as that of the dateString. Then compare the dates using following function.
NSDate *today = [NSDate date]; // current date
NSDate *newDate = self.serverDate; // other date
NSComparisonResult result;
result = [today compare:newDate]; // comparing two dates
if(result == NSOrderedAscending)
NSLog(#"today is less");
else if(result == NSOrderedDescending)
NSLog(#"newDate is less");
else if(result == NSOrderedSame)
NSLog(#"Both dates are same");
else
NSLog(#"Date cannot be compared");
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);
You cannot compare two date string initially you have to convert that string to two date by using the following code
// The current date :2013-06-27 13:51
// The server date :2013-06-27 11:51
NSString *serverDate = #"2013-06-27 13:51";
NSDateFormatter *datePickerFormat = [[NSDateFormatter alloc] init];
[datePickerFormat setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[datePickerFormat setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *convertedDate = [datePickerFormat dateFromString:serverDate];
NSLog(#"date %#",convertedDate);
after conversion you can compare using the following code as said by #prince
NSDate *today = [NSDate date]; // current date
NSDate *newDate = self.serverDate; // other date
NSComparisonResult result;
result = [today compare:newDate]; // comparing two dates
if(result == NSOrderedAscending)
NSLog(#"today is less");
else if(result == NSOrderedDescending)
NSLog(#"newDate is less");
else if(result == NSOrderedSame)
NSLog(#"Both dates are same");
else
NSLog(#"Date cannot be compared");