Through my App users can order specific food item in restaurants..The thing is that if a user want to order a specific product he can give atleast 6 hrs time for the restaurant to deliver the product.For example you are the user,right now time is 12:00pm..In the app,user can select the timings of DELIVERY through UIDatepicker.Here if user selects the time before 06:00pm,one alert view will generate with message "please give 6hrs time for your order".Here i have to compare system time and UIDatepickers time.I found one method,,but it is not useful.
if ([self.datePicker.date compare:currentdate] == NSOrderedDescending){
NSLog(#"Descending");
}
Please help me...Thanks in advance
Either you can compare the selected time by
NSDate *date1 = [NSDate date];
NSDate *date2 = datePicker.date;
NSTimeInterval elapsed = [date1 timeIntervalSinceDate:date2];
Also you can set minimum time of date picker after 6 hours
NSDate *mydate = [NSDate date];
NSTimeInterval secondsInSixHours = 6 * 60 * 60;
NSDate *dateSixHoursAhead = [mydate dateByAddingTimeInterval:secondsInSixHours];
[datePicker setMinimumDate:dateSixHoursAhead];
use this
if ([[NSDate date] isEqualToDate: currentdate) {
NSLog(#"currentDate is equal to currentdate");
}
You are actually looking for time difference , here is the code :
NSLog(#"please give %#fhrs time for your order",[self.datePicker.date timeIntervalSinceDate:[NSDate date]]);
Use this method. The best way of doing comparison between two dates:
- (void)pickerDateIsSmallerThanCurrent:(NSDate *)checkDate
{
NSDate* enddate = checkDate;
NSDate* currentdate = [NSDate date];
NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
double secondsInMinute = 60;
NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
if (secondsBetweenDates == 0)
//both dates are equal
else if (secondsBetweenDates < 0)
//selected date is smaller than current date
else
//selected date is greater than current date
}
Related
There is a object called Place. user can add place to favorite and also user can remove place from the favorite. once user added to the favorite I save date on the database. when user remove from the favorite I retrieve date from the db. and compare particular object with array of objects. but it gives NSOrderedAscending when comparing same object.
NSDate *date1 = obj1.date; // same date
NSDate *date2 = obj2.date; // same date
// compare using date
NSComparisonResult result = [date2 compare:date1];
any help would be appreciate. Thanks.
Try do this:
-(NSDate *)clearSecondsFromDate:(NSDate *)date
{
NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
timeInterval -= fmod(timeInterval, 60);
NSDate *clearDate = [NSDate dateWithTimeIntervalSinceReferenceDate:: timeInterval];
return clearDate;
}
If you want to compare two dates are equivalent to the same second, then get the number of seconds since some epoch and round off the fractional part:
BOOL same = round([date1 timeIntervalSince1970]) ==
round([date2 timeIntervalSince1970]);
Or convert to an integer:
BOOL same = (unsigned long)[date1 timeIntervalSince1970] ==
(unsigned long)[date2 timeIntervalSince1970];
(you can also use [NSDate timeIntervalSinceReferenceDate] if you like, as well).
NSDate doesn't just contain day and seconds, it has a resolution better than microseconds. Your NSDates are probably some fraction of a second apart. Try to log [date1 timeIntervalSinceDate:date2].
So most likely your dates are just not the same. If you are sorting dates, and you want to have dates within the same second considered equal, take
double seconds1 = round ([date1 timeIntervalSinceReferenceDate]);
double seconds2 = round ([date2 timeIntervalSinceReferenceDate]);
which takes the time in a date and rounds it to the nearest second, and compare those values.
I am trying to implement some pseudo code I have for the date picker. However I am unsure of how to add a minute value to adjust an NSDate object.
Here is the pseudo code:
//minTime is an NSDate object
minTime = currentTime + 30mins - (currentTime % 15)
(currentTime % 15) means that the user can only select in 15mins intervals, and must be 15mins from the current 15min interval. For example, if its 10:50, the user should only be able to select 11:15 from the UIDatePicker. If is 10:20, the user should only be able to select 10:45.
I know how to get the currentTime using [NSDate date] but I do not know how to add mins to it and adjust it.
It is not considered good practice to work with time intervals when working with dates and times. The best solution is to use NSDateComponents to add time periods.
NSDateComponents* dc = [NSDateComponents new];
dc.minutes = 15;
NSDate* newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dc toDate:oldDate options:0];
You can add some minutes to a NSDate using :
NSDate *nowDate = [NSDate date];
NSDate *nowDateAnd2moreMinutes = [nowDate dateByAddingTimeInterval:2*60]; //This add 2 minutes (2 * 60sec)
More information in apple documentation.
Edit I wrote a little function that add minutes :
+(NSDate) addMinutes:(int) minutes toDate:(NSDate) date{
return [date dateByAddingTimeInterval:minutes*60];
}
Bonus : Function that add minutes and seconds to a date
+(NSDate) addMinutes:(int) minutes andSeconds:(int) sec toDate:(NSDate) date{
return [date dateByAddingTimeInterval:(minutes*60)+sec];
}
I get a Unix timestamp (Created at time) from server of which I get the NSDate object using :
NSTimeInterval interval = [str doubleValue];
NSDate *timeStamp = [NSDate dateWithTimeIntervalSince1970:interval];
I need to find the time difference between the above created time and current time and display in hh:mm:ss format. I coded it :-
NSTimeInterval timeDiff = [agent.chatStartTimeStamp timeIntervalSinceNow];
// NSDate *now = [NSDate date];
// timeDiff = [now timeIntervalSinceDate:agent.chatStartTimeStamp]; // RETURNS NEGATIVE
// Divide the interval by 3600 and keep the quotient and remainder
div_t h = div(timeDiff, 3600);
int hours = h.quot;
// Divide the remainder by 60; the quotient is minutes, the remainder
// is seconds.
div_t m = div(h.rem, 60);
int minutes = m.quot;
int seconds = m.rem;
NSString *str = [NSString stringWithFormat:#"%d:%d%d", hours, minutes, seconds];
cell.timeLabel.text = str;
NSLog(#"*********** CV CTRL - AGENT CHATSTARTTIME - %# TIME DIFFERNCE = %f STR = %#", agent.chatStartTimeStamp, timeDiff, str);
The logs for the above 2 codes -
AGENT CHATSTART TIME - 1403342129.980000 SET TIME - 2014-06-21 09:15:29 +0000
*********** CV CTRL - AGENT CHATSTARTTIME - 2014-06-21 09:15:29 +0000 TIME DIFFERNCE = 130.419857 STR = 0:210
The above code gives me results as - suppose the value is 0:2:10, then this value reduces to 0:1:40, 0:1:6, 0:-1....
What I am looking out is - the time difference should increase as the created at time will be something before/earlier current time only. So I want that value of startTime should be deducted from now i.e. now - startTime (time). And I believe this will give me results as I am expecting. I tried with [now timeIntervalSinceDate:agent.chatStartTimeStamp]; but that returns negative response.
UPDATE
This is how I convert the unix timestamp to loca time :-
+ (NSDate *)getNSDateFromUnixTimeStamp : (NSString *) unixTime {
NSString *str = [NSString stringWithFormat:#"%f",[unixTime doubleValue]/(double)1000];
NSTimeInterval interval = [str doubleValue];
NSDate *timeStamp = [NSDate dateWithTimeIntervalSince1970:interval];
str = nil;
unixTime = nil;
return timeStamp;
}
And log for the same :-
2014-06-23 12:24:38.046 MintChat[1021:70b] AGENT CHATSTART TIME - 1403506610.771000 SET TIME - 2014-06-23 06:56:50 +0000
My system time is 12:24:38 & the unixtimestamp is also the current time at just few secs before, so I guess shouldn't the unix time set should also have time as almost same.
Can anyone help me how to get this simple time difference. Where am I going wrong ? I searched a lot on the subject, but couldn't get the expected results.
Any help is highly appreciated.
Thanks
Your commented code, [now timeIntervalSinceDate:agent.chatStartTimeStamp]; is correct. From the NSDate documentation -
Return Value
The interval between the receiver and the current date and time. If the receiver is earlier than the current date and
time, the return value is negative.
So, you can simply take the absolute value to get the number of seconds -
NSTimeInterval timeDiff = fabs([now timeIntervalSinceDate:agent.chatStartTimeStamp]);
Once you have the time interval you can use this answer to format it -
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeDiff];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
NSString *formattedDate = [dateFormatter stringFromDate:date];
NSLog(#"hh:mm:ss %#", formattedDate);
I am trying to perform a segue in Objective-C (XCode) for iOS devices, when the time right now is between two other fixed times. Just like "Open Hours" for stores - when the time right now is between open and close hour.
Here is the code I have been working on - some of the code may look familiar, because I found some useful stuff on SO which helped me - but still I can't get it to work. It doesn't perform the segue when the time passes startTime. It should be in the specified time interval.
The time is in 24-hour format.
// set start time and end time
NSString *startTimeString = #"23:00";
NSString *endTimeString = #"05:00";
// set date formatter 24-hour format
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"HH:mm"];
// german timezone
NSLocale *locale = [[NSLocale alloc]initWithLocaleIdentifier:#"de_DE"];
NSString *nowTimeString = [formatter stringFromDate:[NSDate date]];
// set NSDates for startTime, endTime and nowTime
NSDate *startTime = [formatter dateFromString:startTimeString];
NSDate *endTime = [formatter dateFromString:endTimeString];
NSDate *nowTime = [formatter dateFromString:nowTimeString];
[formatter setLocale:locale];
// compare endTime and startTime with nowTime
NSComparisonResult result1 = [nowTime compare:endTime];
NSComparisonResult result2 = [nowTime compare:startTime];
if ((result1 == NSOrderedDescending) &&
(result2 == NSOrderedAscending)){
NSLog(#"Time is between");
[self performSegueWithIdentifier:#"openHours" sender:self];
} else {
NSLog(#"Time is not between");
}
thanks for taking your time to look at my question. I have been searching and searching, trying and trying, but no luck in making it work yet. Hopefully your answers will help me.
You should little bit change you code
// set NSDates for startTime, endTime and nowTime
int startTime = [self minutesSinceMidnight:[formatter dateFromString:startTimeString]];
int endTime = [self minutesSinceMidnight:[formatter dateFromString:endTimeString]];
int nowTime = [self minutesSinceMidnight:[formatter dateFromString:nowTimeString]];;
[formatter setLocale:locale];
if (nowTime < endTime && nowTime > startTime) {
NSLog(#"Time is between");
} else if (nowTime > endTime && nowTime < startTime) {
NSLog(#"Time is between");
} else {
NSLog(#"Time is not between");
}
And implement method for calculating time:
-(int) minutesSinceMidnight:(NSDate *)date
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
unsigned unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:date];
return 60 * [components hour] + [components minute];
}
I am interested in an answer that works on ANY date, and not fixed dates for opening and closing.
In that case the simplest approach would be using NSDateComponents. You could store hour, minutes and maybe weekday for opening and closing. to check for now you would break up [NSDate now] into the same NSDateComponents and cop are those.
I have a current NSString in the format of 2010-04-23 00:00:00 and then I'm trying to get the number of days passed from the current day. However, I'm not sure how to handle when the user changes their locale to Thailand for example.
Here is some of the code.
NSString *start = #"2010-04-23 00:00:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSDate *date = [formatter dateFromString:start];
//Region Format Thailand
NSDate *today = [[NSDate alloc] init];
NSTimeInterval difference = [today timeIntervalSinceDate:start];
int numberOfDays = difference / 86400;
What would be the correct way to handle this situation so the number of days difference is accurate?
Dates are complicated.
If you want a difference in days, hours, minutes, seconds, that's easy: Convert everything to NSDate, calculate the difference in seconds, convert to days, hours, minutes, seconds.
Anything else, you need to first define what results you actually want. Today at 1am and 11pm is the same day, but today 11pm and tomorrow 1am are different days - even though in the first case the difference is 22 hours, in the second case just two hours. So you have to define what you want. You have to define for which case you want a result of "0 days" and for which case you want a result of "1 days".
And if you change time zones, some dates will move to a different day, some won't.
It's up to you to decide what result you want. In any case, I'd convert all dates to the relevant time zone, extract the day, and calculate days differences from that.
You need to convert the date into epoch time.
- (NSTimeInterval)timeIntervalSince1970
After you do that you can use the below code, to find the time difference in seconds and compare them.
NSDate* date1 = [NSDate date];
NSDate* date2 = [NSDate date];
NSTimeInterval secs = [date1 timeIntervalSinceDate:date2];
if (secs < 0)
{
NSLog("less");
}
else if (secs > 0)
{
NSLog("greater");
}
else
{
NSLog(#"same");
return NSOrderedSame;
}