How to calculate NSDate between two NSDate in IOS - ios

I want show whether particular office is opened or closed depends on the weekday
i am getting office timings from my server
NSString *open = #"10:00 AM";
NSString *close = #"6:00 PM";
NSDateFormatter *df11 = [[NSDateFormatter alloc]init];
[df11 setDateFormat:#"dd-MM-yyyy"];
NSString *date11=[df11 stringFromDate:[NSDate date]];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"dd-MM-yyyy hh:mm a"];
NSDate *date1 = [NSDate date];
NSString *dte1 = [df stringFromDate:date1];
date1 = [df dateFromString:dte1];
NSString *dte2 = [NSString stringWithFormat:#"%# %#",date11, open];
NSDate *date2 = [df dateFromString:dte2];
NSString *dte3 = [NSString stringWithFormat:#"%# %#",date11,close];
NSDate *date3 = [df dateFromString:dte3];
if([date1 compare:date2]==NSOrderedDescending && [date1 compare:date3]==NSOrderedAscending)
open=YES;
else
open=NO;
In this case i didn't get any problem, but for some other office i got like this
NSString *open = #"11:30 AM";
NSString *close = #"12:30 AM";/*means here day is changing but still i am using current date
for this case the above code is not working, bcoz of day changes, i am not getting any idea how to follow, i was struggling from last day for solution
please help me
thank you

get days between two dates
NSDate *date1 = [NSDate dateWithString:#"2013-08-08"];
NSDate *date2 = [NSDate dateWithString:#"2013-09-09"];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfDays = secondsBetween / 86400;
NSLog(#"There are %d days in between the two dates.", numberOfDays);
You can also get different between two dates GO

Extract the week day and hour from the date and do an explicit test on them:
const NSInteger openHour = 10;
const NSInteger closeHour = 18;
NSDate *dateToTest = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit|NSHourCalendarUnit
fromDate:dateToTest];
BOOL open =
[components weekDay] >= [calendar firstWeekDay] &&
[components weekDay] < [calendar firstWeekDay] + 5 &&
[components hour] >= openHour &&
[components hour] < closeHour;

Related

How to calculate remaining Days, Hours, Mins and seconds from given date?

In my app I need to get the days, hours, minutes and seconds from a given date which is coming from JSON response. Below is the date and time i'm getting:
"date_time" = "2017-01-31 08:30:00";
and need to calculate remaining like days: 6 hours: 18 minutes: 24 seconds: 30
End date will be today's date. I tried below code but it is giving me days in minus (I think it takes UTC timezone) and also tried many answers on SO.
NSString *start = [[self.eventsArray valueForKey:#"date_time"]objectAtIndex:0];
NSDateFormatter *date = [[NSDateFormatter alloc] init];
[date setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *end = [date stringFromDate:[NSDate date]];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
fromDate:startDate
toDate:endDate
options:0];
NSLog(#"day : %ld H: %ld M : %ld S:%ld", [components day], (long)[components hour],(long)[components minute],(long)[components second]);
Somebody please help i'm stuck.
You are making mistake here, your fromDate should be the today date ie [NSDate date] and with toDate will be your startDate. So your code should be something like this.
NSString *end = [[self.eventsArray valueForKey:#"date_time"]objectAtIndex:0];
NSDateFormatter *date = [[NSDateFormatter alloc] init];
[date setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
//Start date
NSDate *startDate = [NSDate date];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond
fromDate:startDate
toDate:endDate
options:0];
NSLog(#"day : %ld H: %ld M : %ld S:%ld", [components day], (long)[components hour],(long)[components minute],(long)[components second]);
Call below method and pass your date
+(NSMutableString*) timeLeftSinceDate: (NSDate *) dateT {
NSMutableString *timeLeft = [[NSMutableString alloc]init];
NSDate *today10am = [NSDate date];
today10am = [self getPickerDateForString:[self getPickerDateForDate:today10am]];
NSInteger seconds = [today10am timeIntervalSinceDate:dateT];
NSInteger days = (int) (floor(seconds / (3600 * 24)));
if(days) seconds -= days * 3600 * 24;
NSInteger hours = (int) (floor(seconds / 3600));
if(hours) seconds -= hours * 3600;
NSInteger minutes = (int) (floor(seconds / 60));
if(minutes) seconds -= minutes * 60;
if(days) {
[timeLeft appendString:[NSString stringWithFormat:#"%ld Days ago", (long)days]];
}else if(hours) {
[timeLeft appendString:[NSString stringWithFormat: #"%ld h ago", (long)hours]];
}else if(minutes) {
[timeLeft appendString: [NSString stringWithFormat: #"%ld m ago",(long)minutes]];
}else if(seconds) {
[timeLeft appendString:[NSString stringWithFormat: #"Just now"]];
}
return timeLeft;
}
+ (NSString *)getPickerDateForDate:(NSDate *)dateVal
{
NSString * stringVal;
if (!dateFormatter)
{
dateFormatter = [[NSDateFormatter alloc] init];
}
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
stringVal = [dateFormatter stringFromDate:dateVal];
return stringVal;
}
+ (NSDate *)getPickerDateForString:(NSString *)dateString
{
NSDate * stringVal;
if (!dateFormatter)
{
dateFormatter = [[NSDateFormatter alloc] init];
}
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
dateFormatter.timeZone = [NSTimeZone systemTimeZone];
stringVal = [dateFormatter dateFromString:dateString];
return stringVal;
}

How to get NSDate start of previous month?

I suppose that I ask duplicate question, but I can not find solution for me. I need to get 1st day of the previous month. As I understand I have to get calendar from today, subtract 1 month and set day to be 1st. After that I have to convert to date. Unfortunately I get last day of previous month.
I use following code:
NSDate *maxDate = [[NSDate alloc] init];
NSCalendar *calendarCurr = [NSCalendar currentCalendar];
NSDateComponents *components = [calendarCurr components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:maxDate];
[components setMonth:-1];
components.day = 1;
NSDate *minDate = [calendarCurr dateFromComponents:components];
NSLog(#"%#", minDate);
EDIT:
Yes, it is duplicate, but answers in that question does not help me. I still get 30/09/2014 (when today is 17/11/2014) instead of 01/10/2014. I suppose that my problem is time of todays date.
Well, Here a new approach:
NSDate *today = [NSDate date];
NSDateFormatter *formatterYear = [[NSDateFormatter alloc] init];
[formatterYear setDateFormat:#"yyyy"];
NSDateFormatter *formatterMonth = [[NSDateFormatter alloc] init];
[formatterMonth setDateFormat:#"MM"];
[formatterMonth setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSString *yearString = [formatterYear stringFromDate:today];
NSString *monthString = [formatterMonth stringFromDate:today];
NSInteger month,year;
if ([monthString integerValue] == 1) {
year = [yearString integerValue] -1;
month = 12;
} else
{
year = [yearString integerValue];
month = [monthString integerValue]-1;
}
NSDateFormatter *exitFormatter = [[NSDateFormatter alloc] init];
[exitFormatter setDateFormat:#"yyyy-MM-dd"];
[exitFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSString *stringDate;
if (month < 10) {
stringDate = [NSString stringWithFormat:#"%ld-0%ld-01",(long)year,(long)month];
} else {
stringDate = [NSString stringWithFormat:#"%ld-%ld-01",(long)year,(long)month];
}
NSDate *firstDatePreviousMonth = [exitFormatter dateFromString:stringDate];
NSLog(#"View the date: %#",[firstDatePreviousMonth description]);
Wrong calculation.
Use this code to set Month component.
[components setMonth:components.month -1];
NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
[dateFormatter1 setDateFormat:#"MM"];
NSString *stringCurrentDate = [dateFormatter1 stringFromDate:currentDate];
int monthInt= [stringCurrentDate intValue];
[dateFormatter1 setDateFormat:#"yyyy"];
NSString *dateString = [dateFormatter1 stringFromDate:currentDate];
int yearInt = [dateString intValue];
monthInt-= 1;
if (monthInt== 0) {
monthInt= 12;
yearInt -=1;
}
dateString = [NSString stringWithFormat:#"%#-01-%#",[#(monthInt)stringValue],[#(yearInt)stringValue]];
NSLog(#"this is previous month first date : %#",dateString);
run it as it is, obviously first day of month will be 01, so this is static here. your can change accordingly. happy coding
Try this:
NSDate *maxDate = [NSDate date];
NSCalendar *calendarCurr = [NSCalendar currentCalendar];
NSDateComponents *components = [calendarCurr components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitTimeZone | NSCalendarUnitSecond | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:maxDate];
[components setMonth:components.month - 1];
[components setDay:1];
NSDate *minDate = [calendarCurr dateFromComponents:components];
NSLog(#">>>>>>>>>>%#", minDate.description);

Conversion of NSString to NSDate conversion - incorrect result

In short words I plan to get current dateTime, change the time and make it local to Malaysia Time by applying +0800 to timezone.
The result is unexpected :
-(NSDate *)departureDateTime
{
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setHour: 7];
[components setMinute: 59];
[components setSecond: 17];
NSDate *newDate = [gregorian dateFromComponents: components];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-mm-dd HH:mm:ss Z"];
[dateFormat setLocale:[NSLocale currentLocale]];
NSString *newDateString = [NSString stringWithFormat:#"%#",newDate];
NSString *maskString = [NSString stringWithFormat:#"%#", [newDateString substringToIndex:20]];
NSString *append = [maskString stringByAppendingString:#"+0800"];
NSLog(#"%#",append);
NSDate *finalLocalDate = [dateFormat dateFromString:append];
return finalLocalDate;
}
Results :
for NSLog Append : 2013-12-07 23:59:17 +0800
but finalLocalDate : 2013-01-07 15:59:17 +0000
Found the answer with much shorter solution, so I posted here in case it helps anyone in future.
for returning, the problem was different time zones so by adding this line of
[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:(+0*3600) ] ];
we set the timezone to system time zone then we remove unnecessary codes :
-(NSDate *)departureDateTime
{
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:(+0*3600) ] ];
[components setHour: 7];
[components setMinute: 59];
[components setSecond: 17];
NSDate *newDate = [gregorian dateFromComponents: components];
NSLog(#"%#",newDate);
return newDate;
}
Correct Result : 2013-12-08 07:59:17 +0000
try this:
NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
NSDate *malaysianTime = [NSDate dateWithTimeIntervalSince1970:now+(8*60*60)]; //8h in seconds
If your computer is running in the correct timezone don't set a timezone.
Create your newDate value and then --
NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSString* printableDate = [fmt stringFromDate:newDate];
NSLog(#"The date is %#", printableDate);
Only set a timezone (in both NSCalendar and NSDateFormatter) if the desired timezone is not the one your computer/phone is currently using.
Note that if you NSLog newDate directly it will print in GMT timezone. This is the way it's supposed to be -- you always use NSDateFormatter for a printable date. When you NSLog an NSDate directly you get GMT, by design.

Get time from pressed button (hold pressed)

When trying to get the time, I am not getting the expected value.
When I ran this, the time was 19:59. And in the timeDifferenceString, the Value was 71976.894206.
I think that this is the current time.
I calculate 71976 / 3600 = 19,99 h
0,99 * 60 = 59,4 m
0,4 * 60 = 24 s
So I get the time 19:59:24 o'clock. But I want get the difference between the first time and the second time and not the current time in seconds.
I want only get the time when I (hold) pressed the button
and the time that the button is not pressed (by starting the first time if I press on the button and stopped if I press on an other button).
- (IBAction)pressTheButton:(id)sender {
NSDate * now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm:ss:SSS"];
NSString *currentTime = [formatter stringFromDate:now];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components; //= [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
[components setHour:10];
NSDate* firstDate = [NSDate date];
NSString *getTime = [formatter stringFromDate:now];
getTime = [formatter stringFromDate:firstDate];
if (iX==0)
{
components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
firstDate = [calendar dateFromComponents:components];
getTime = [formatter stringFromDate:firstDate];
//firstDate = [NSDate date];//[dateFormatter dateFromString:#"00:01:00:090"];
}
components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
//NSDate* secondDate = [dateFormatter dateFromString:#"10:01:02:007"];
NSDate * secondDate = [calendar dateFromComponents:components];
getTime = [formatter stringFromDate:firstDate];
NSTimeInterval timeDifference = [firstDate timeIntervalSinceDate:secondDate];
NSString *timeDifferenceString = [NSString stringWithFormat:#"%f", timeDifference];
timeDiff[iX] = [timeDifferenceString intValue];
[timeLabel setText:timeDifferenceString];
iX++;
}
If you have a better solution for my problem pleas help me.
Look at UIControlEventTouchDown, UIControlEventTouchUpInside here: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIControl_Class/Reference/Reference.html
Then I suppose you want to store an NSDate of when you pressed down in some sort of ivar or property (UIControlEventTouchDown) and another one when you release the button (UIControlEventTouchUpInside or UIControlEventTouchUpOutside) and then call -timeIntervalSinceDate: on that date. So it would look roughly like this:
- (IBAction)pressedDown:(id)sender {
self.pressedDownDate = [NSDate date];
}
- (IBAction)touchedUp:(id)sender {
NSDate *now = [NSDate date];
NSLog(#"Time passed: %d", [now timeIntervalSinceDate:self.pressedDownDate]);
}

how to find days remaning in birthdate [duplicate]

This question already has answers here:
Calculate number of days remaining [duplicate]
(5 answers)
Closed 8 years ago.
i want to remaning days from array of birthdates im using following code for it
for(int i =0;i<_convertedBdates.count;i++){
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:#"dd/MM/YYYY"];
NSDate *firstdate = [tempFormatter dateFromString:[_convertedBdates objectAtIndex:i]];
NSString *curYear = [tempFormatter stringFromDate:[NSDate date]];
NSDate *secondDate = [tempFormatter dateFromString:curYear];
NSTimeInterval lastDiff = [firstdate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [secondDate timeIntervalSinceNow];
NSTimeInterval dateDiff = lastDiff - todaysDiff;
int day = dateDiff/(3600*24);
NSLog(#" _newlymadeArray %#",[_convertedBdates objectAtIndex:i]);
NSLog(#" days %d",day);
[_daysremaining addObject:[NSString stringWithFormat:#"%d",day] ];
}
NSLog(#" days %#",_daysremaining);
what wrong i am doing why i am not getting correct days
for(int i =0;i<_convertedBdates.count;i++){
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:#"dd/MM/YYYY"];
NSDate *firstdate = [tempFormatter dateFromString:[_convertedBdates objectAtIndex:i]];
NSString *curYear = [tempFormatter stringFromDate:[NSDate date]];
NSDate *secondDate = [tempFormatter dateFromString:curYear];
NSTimeInterval lastDiff = [firstdate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [secondDate timeIntervalSinceNow];
NSTimeInterval dateDiff = lastDiff - todaysDiff;
int day = dateDiff/(3600*24);
day = day -1;
NSLog(#" _newlymadeArray %#",[_convertedBdates objectAtIndex:i]);
NSLog(#" days %d",day);
[_daysremaining addObject:[NSString stringWithFormat:#"%d",day] ];
}
NSLog(#" days %#",_daysremaining);
try like this it will help you,
NSString *start = #"03/12/2013";
NSString *end = #"09/12/2013";
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"dd/mm/yyyy"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
NSLog(#"%d",[components day]);
Keep your code simple :
You can use a method and call it within your calculation block:
- (NSInteger)daysBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime{
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar=[NSCalendar currentCalendar];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:fromDateTime];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:toDateTime];
NSDateComponents *difference = [calendar components:NSDayCalendarUnit
fromDate:fromDate toDate:toDate options:0];
return [difference day];
}

Resources