This question already has answers here:
Check whether time falls between two time iOS
(2 answers)
Closed 6 years ago.
I have an object with 2 String properties: notifyFrom and notifyTo.
They are like:
notifyFrom: 14:00
notifyTo: 18:00
and before I send the user a notification (that's part of my app) I want to check if the time is between those hours and just if it is to send the notification.
Note: Date doesn't matter here. I just want to check the times
What is the best way to do it?
Thanks!
You can write method something like,
+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
if ([date compare:beginDate] == NSOrderedAscending)
return NO;
if ([date compare:endDate] == NSOrderedDescending)
return NO;
return YES;
}
Reference : this so post
First of all convert the input two strings to dates
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *date1 = [dateFormatter dateFromString:notifyFrom];
NSDate *date2 = [dateFormatter dateFromString:notifyTo];
NSDate *userDate = [NSDate date];
if (([userDate laterDate: date1] == userDate) && ([userDate laterDate: date2] == date2)){
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have to compare date (coming from server) with today's date. The date from server is in different format (that is, date format may be 2015-09-08 or 2015-09-08T11:30:00+0530)
How can we compare these different date format with today's date in iOS (Objective-C).
Actually, there is no matter if you want to compare 2 dates in different formats, the problem is to compare date values you have to ensure
1. They are converted to the same timezone.
2. Use - (NSComparisonResult)compare:(NSDate *)anotherDate method
In addition, if you want to convert your date string response from HE to NSDate, you can do as below
+ (NSDate *)dateFromDateString:(NSString *)dateString withFormat:(NSString *)format {
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = format;
return [formatter dateFromString:dateString];
}
Moreover, in term of comparing 2 dates in specific components (such as year, month, day and without hour, min or second) you have to use NSDateComponents
- (BOOL)date:(NSDate *)aDate isEqualToDateIgnoringTime:(NSDate *) anotherDate
{
NSCalendarUnit unitFlags = (NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond);
NSDateComponents *components1 = [[NSCalendar currentCalendar] components:unitFlags fromDate:aDate];
NSDateComponents *components2 = [[NSCalendar currentCalendar] components:unitFlags fromDate:anotherDate];
return ((components1.year == components2.year) && (components1.month == components2.month) && (components1.day == components2.day));
}
try with this
-(void)dateFormateTest{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy-MM-dd HH:mm:ss Z";
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone defaultTimeZone]];
[NSTimeZone resetSystemTimeZone];
NSDate *date = [formatter dateFromString:#"2015-10-06 12:39:12"];
NSLog(#"date: %#",date);
NSComparisonResult result = [date compare:[NSDate date]];
if (result == NSOrderedDescending) {
NSLog(#"Past");
}else if (result == NSOrderedDescending) {
NSLog(#"future");
}
}
Comparing dates is quite complex. I have an app that is comparing opening and closing dates for stores and it works great for times in the same day, i.e. opening a 8am and closing at 5pm the same day.
Here is the code that compares the time:
if ([self timeCompare:openDate until:closeDate withNow:now]) {
NSLog(#"TIMECOMPARATOR = timeCompare>OPEN");
status = YES;
} else {
NSLog(#"TIMECOMPARATOR = timeCompare>CLOSED");
status = NO;
}
return status;
This calls the following method:
+(BOOL)timeCompare:(NSDate*)date1 until:(NSDate*)date2 withNow:(NSDate*)now{
NSLog(#"TIMECOMPARE = open:%# now:%# close:%#", date1, now, date2);
return ([date1 compare:now] == NSOrderedAscending && [date2 compare:now] == NSOrderedDescending);
}
The problem comes when the closing time is "assumed" by a person but of course not by a computer, to close at the next day, such as 7am to 2am. I obviously mean the next day. How do I accommodate for this to signal the computer to be the next day?
Compare the date's unix time. It will be accurate regardless of date as it is constantly increasing.
First you have to convert the strings "7:00 AM", "10:00 PM" to a NSDate from the current day. This can be done e.g. with the following method:
- (NSDate *)todaysDateFromAMPMString:(NSString *)time
{
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setLocale:[NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"]];
// Get year-month-day for today:
[fmt setDateFormat:#"yyyy-MM-dd "];
NSString *todayString = [fmt stringFromDate:[NSDate date]];
// Append the given time:
NSString *todaysTime = [todayString stringByAppendingString:time];
// Convert date+time string back to NSDate:
[fmt setDateFormat:#"yyyy-MM-dd h:mma"];
NSDate *date = [fmt dateFromString:todaysTime];
return date;
}
Then you can proceed as in https://stackoverflow.com/a/20441330/1187415:
// Some example values:
NSString *strOpenTime = #"10:00 PM";
NSString *strCloseTime = #"2:00 AM";
NSDate *openTime = [self todaysDateFromAMPMString:strOpenTime];
NSDate *closeTime = [self todaysDateFromAMPMString:strCloseTime];
if ([closeTime compare:openTime] != NSOrderedDescending) {
// closeTime is less than or equal to openTime, so add one day:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [[NSDateComponents alloc] init];
[comp setDay:1];
closeTime = [cal dateByAddingComponents:comp toDate:closeTime options:0];
}
NSDate *now = [NSDate date];
if ([now compare:openTime] != NSOrderedAscending &&
[now compare:closeTime] != NSOrderedDescending) {
// Shop is OPEN
} else {
// Shop is CLOSED
}
This is an app design question, not a coding question. You need to define a clear vocabulary for the user to communicate what they mean. I would suggest adding a UISwitch to the screen, with 2 positions on it: "Today" and "Tomorrow". You can add some program logic that takes a guess as to times where you think the user is talking about a date tomorrow, and set the default switch to the "tomorrow" state in that case, but the user should be able to tell you what they mean.
How about you just add a check whether all the three NSDate are having the same date (DDMMYYYY) value?
This question already has answers here:
Comparing time and date in objective C
(2 answers)
Closed 9 years ago.
In my app i want to check whether the current time is before or after the time saved in a variable.
like my time1 is time1=#"08:15:12"; and my time2 is time2=#"18:12:8";
so i wanna compare between time1 and time2.Currently these variables are in NSString Format.
Following are the code used to get time,and i dont know how to compare them.
CODE:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"HH:MM:SS";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(#"ewetwet%#",[dateFormatter stringFromDate:now]);
Please help me
Use the following code to do the convert from the nsstring to nsdate and compare them.
NSString *time1 = #"08:15:12";
NSString *time2 = #"18:12:08";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *date1= [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
NSComparisonResult result = [date1 compare:date2];
if(result == NSOrderedDescending)
{
NSLog(#"date1 is later than date2");
}
else if(result == NSOrderedAscending)
{
NSLog(#"date2 is later than date1");
}
else
{
NSLog(#"date1 is equal to date2");
}
// Use compare method.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *startDate = [formatter dateFromString:#"2012-12-07 7:17:58"];
NSDate *endDate = [formatter dateFromString:#"2012-12-07 7:17:59"];
if ([startDate compare: endDate] == NSOrderedDescending) {
NSLog(#"startDate is later than endDate");
} else if ([startDate compare:endDate] == NSOrderedAscending) {
NSLog(#"startDate is earlier than endDate");
} else {
NSLog(#"dates are the same");
}
// Way 2
NSTimeInterval timeDifference = [endDate timeIntervalSinceDate:startDate];
double minutes = timeDifference / 60;
double hours = minutes / 60;
double seconds = timeDifference;
double days = minutes / 1440;
NSLog(#" days = %.0f,hours = %.2f, minutes = %.0f,seconds = %.0f", days, hours, minutes, seconds);
if (seconds >= 1)
NSLog(#"End Date is grater");
else
NSLog(#"Start Date is grater");
First you need to convert your time string to NSDate => Converting time string to Date format iOS.
Then use following code
NSDate *timer1 =...
NSDate *timer2 =...
NSComparisonResult result = [timer1 compare:timer2];
if(result == NSOrderedDescending)
{
// time 1 is greater then time 2
}
else if(result == NSOrderedAscending)
{
// time 2 is greater then time 1
}
else
{
//time 1 is equal to time 2
}
You can use this link
According to Apple documentation of NSDate compare:
Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.
- (NSComparisonResult)compare:(NSDate *)anotherDate
Parameters anotherDate
The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.
Return Value
If:
The receiver and anotherDate are exactly equal to each other, NSOrderedSame
The receiver is later in time than anotherDate, NSOrderedDescending
The receiver is earlier in time than anotherDate, NSOrderedAscending
In other words:
if ([date1 compare:date2]==NSOrderedSame) ...
Note that it might be easier to read and write this :
if ([date2 isEqualToDate:date2]) ...
See Apple Documentation about this one. If you feel any problem you can also use this link here. Here you can go through Nelson Brian answer.
I have done this at my end as follows-
NSDate * currentDateObj=#"firstDate";
NSDate * shiftDateFieldObj=#"SecondDate";
NSTimeInterval timeDifferenceBetweenDates = [shiftDateFieldObj timeIntervalSinceDate:currentDateObj];
You can also get time interval according to time difference between dates.
Hope this helps.
This question already has answers here:
How to compare two NSDates: Which is more recent?
(13 answers)
Closed 9 years ago.
I am trying to compare two dates whether which one is the new or old, my dates are in following format:
2013-06-03 09:30:35
(YYYY-MM-DD HH:MM:SS)
Please give me some ideas, both are currently in string format?
So is that possible to convert ad check?
Convert that strings into NSDate using dateFormatter.
You can check this link Here is good discussion of your problem
How to compare two NSDates: Which is more recent?
try this
NSString to NSDate
NSString *dateString = #"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];
NSDate convert to NSString:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"%#", strDate);
[dateFormatter release];
Please read this
enter link description here
if ([yourFirstDate compare:secondDate] == NSOrderedDescending) {
NSLog(#"yourFirstDate is later than secondDate");
} else if ([yourFirstDate compare:secondDate] == NSOrderedAscending) {
NSLog(#"yourFirstDate is earlier than secondDate");
} else {
NSLog(#"dates are the same");
}
same as #DIVYU 's Link
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
If “a == b” is false when comparing two NSString objects?
In an "if" statement I'm comparing two strings, "currentDateString" and "dateCreatedString", to get "Today" if true and "dateCreatedString" if false. Although they should be equal when creating a new item, the if statement is returning false every time and just giving the currentDateString when I'm looking to get "today".
- (NSString *)dateCreatedString
{
// Create a NSDateFormatter that will turn a date into a simple date string
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString *dateCreatedString = [dateFormatter stringFromDate:[_detailItem dateCreated]];
return dateCreatedString;
}
- (NSString *)currentDateString
{
// Create a NSDateFormatter that will turn a date into a simple date string
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString *currentDateString = [dateFormatter stringFromDate:[NSDate date]];
return currentDateString;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//places "Today" in the dateLabel if the two strings both equal today
if ([self currentDateString] == [self dateCreatedString] || [_detailItem dateCreated] == nil) {
[_dateTxt setText:#"Today"];
}
else{
[_dateTxt setText:[self dateCreatedString]];
}
}
Could somebody help explain why this is happening, and how to fix it?
Thanks!
You should use isEqualToString to compare strings like this:
if ([[self currentDateString] isEqualToString:[self dateCreatedString]])
Using == you are comparing the pointers to the string objects, which certainly are not the same.