How to get accuracy days completed - ios

How to get accuracy days completed?
- (CGFloat)accuracyDaysCompleted:(NSString *)startDate and:(NSString *)endDate {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
fromDate:[dateFormatter dateFromString:startDate]
toDate:[dateFormatter dateFromString:endDate]
options:0];
return (CGFloat)components.day;
}
Example
The work is completed 3 days 12 hours 30Min
Expected result 3.55 Days.

The following example shows the days difference from the given date and today.
This might guide you to convert seconds, minutes, hours to days.
-(NSString*)timeDifferenceConversion:(NSString*)dateString
{
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate* firstDate = [dateFormatter dateFromString:dateString];
NSDate * now = [NSDate date];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *newDateString = [dateFormatter stringFromDate:now];
NSDate* secondDate = [dateFormatter dateFromString:newDateString];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
NSInteger ti = (NSInteger)timeDifference;
NSInteger minutes = (ti / 60) % 60;
NSInteger hours = (ti / 3600);
NSInteger days = (ti / 86400);
NSString* temp=#"";
if(minutes<=2 && hours<1 && days<1)
{
temp=#"now";
}
else if(minutes>2 && hours<1 && days<1)
{
temp=[NSString stringWithFormat:#"%ld minutes ago", (long)minutes];
}
else if(hours<=24 && days<1)
{
temp=[NSString stringWithFormat:#"%ld hours ago", (long)hours];
}
else if(days<=1)
{
temp=[NSString stringWithFormat:#"%ld day ago",(long)days];
}
else if(days>1)
{
temp=[NSString stringWithFormat:#"%ld days ago",(long)days];
}
return temp;
}

I suggest you calculate the difference in seconds between the two dates, then simply divide the result by the number of seconds in one day :
- (CGFloat)accuracyDaysCompleted:(NSString *)startDate and:(NSString *)endDate {
NSDate *date1 = [NSDate dateWithString: startDate];
NSDate *date2 = [NSDate dateWithString: endDate];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
return secondsBetween / 86400.0f;
}

Related

Find different between hours

I have two hours and minutes :
I got this time from user. that what is your start time and end time.
1) 10:00 AM
2) 06:00 PM
Now i have to find total time user worked for. Means it fetch
total time: 8:00
How do i get it ?
I am ding this code in Objective C.
I think it will help you.
NSString *time1 = #"10.00 pm";
NSString *time2 = #"06.00 pm";
NSDate *date1;
NSDate *date2;
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh.mm a"];
date1 = [formatter dateFromString:time1];
date2 = [formatter dateFromString:time2];
[formatter release];
}
NSTimeInterval interval = [date1 timeIntervalSinceDate: date2]; //[date1 timeIntervalSince1970] - [date2 timeIntervalSince1970];
int hour = interval / 3600;
int minute = (int)interval % 3600 / 60;
NSLog(#"%# %dh %dm", interval<0?#"-":#"+", ABS(hour), ABS(minute));
Try like this!
let calendar = NSCalendar.current
let datecomponents = calendar.dateComponents([.hour], from: start as Date, to: someDateTime as Date)
let hours = datecomponents.hour!
print("hours: \(hours)")
Try this function
-(NSString *)startTime:(NSString *)startTime AndWithAndTime:(NSString *)endTime{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm a"];
NSDate *date1 = [formatter dateFromString:startTime];
NSDate *date2 = [formatter dateFromString:endTime];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
int hours = (int)interval / 3600; // integer division to get the hours part
int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
NSString *timeDiff = [NSString stringWithFormat:#"%d:%02d", hours, minutes];
return timeDiff;
}
NSLog(#"%#",[self startTime:#"10:00 AM" AndWithAndTime:#"06:00 PM"]);

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 check the date cross the sunday and rest data

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;
}
}
}

NSTimeInterval display incorrect time interval

After adding a comment i need to show comment timing like year ago,day ago,minutes ago and second ago on label but it returns -4425,-33434 seconds ago "random numbers".
Here is my code shown below am using in my app.
NSString *inDateStr = [NSString stringWithFormat:#"%#",[[[dict objectForKey:#"d"] objectAtIndex:indexPath.row-1] objectForKey:#"created"]];
NSString *s = #"yyyy-MM-dd HH:mm:ss";
// about input date(GMT)
NSDateFormatter *inDateFormatter = [[NSDateFormatter alloc] init];
inDateFormatter.dateFormat = s;
inDateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT-7.00"];
NSDate *inDate = [inDateFormatter dateFromString:inDateStr];
// about output date(IST)
NSDateFormatter *outDateFormatter = [[NSDateFormatter alloc] init];
outDateFormatter.timeZone = [NSTimeZone localTimeZone];
outDateFormatter.dateFormat = s;
NSString *outDateStr = [outDateFormatter stringFromDate:inDate];
// final output
NSLog(#"[in]%# -> [out]%#", inDateStr, outDateStr);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *dateStartingString = [[NSDate alloc] init];
NSString *datestartString = outDateStr;
dateStartingString = [dateFormatter dateFromString:datestartString];
NSTimeInterval timeDifference = [[NSDate date] timeIntervalSinceDate:dateStartingString];
double minutes = timeDifference / 60;
double hours = minutes / 60;
double seconds = timeDifference;
double days = minutes / 1440;
UILabel * dateLbl=[[UILabel alloc] initWithFrame:CGRectMake(155, [[CountArr objectAtIndex:indexPath.row] floatValue]-1, 80, 20)];
if(seconds>=86400)
dateLbl.text=[NSString stringWithFormat:#"%.0f days ", days];
else if(seconds>=3600 && seconds<86400 )
dateLbl.text=[NSString stringWithFormat:#"%.0f hours ", hours];
else if (seconds>=60 && seconds<3600 )
dateLbl.text=[NSString stringWithFormat:#"%.0f minutes ", minutes];
else
dateLbl.text=[NSString stringWithFormat:#"%.0f seconds ", seconds];
dateLbl.textColor=[UIColor lightGrayColor];
dateLbl.font = [UIFont systemFontOfSize:12];
[cell.contentView addSubview:dateLbl];
I believe NSDateFormatter only takes a string and returns a NSDate object. Setting the timezone is meant for setting the property of NSDate, but doesn't actually convert the time provided. So in the end if you put in 5:30 GMT, you will get 5:30 IST.
You would instead want to use NSCalender to do timezone conversions.
You can use this method to get difference in date.
Make sure that date formate is correct. If you are getting negative value just check date format.
-(NSDateComponents *)getDateDifference:(NSString *)date
{
NSDate *dateA=[NSDate date]; //Current date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateB = [dateFormatter dateFromString:date];//Convert nsstring to nsdate
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; //Gregorian allocation
NSDateComponents *components = [calendar components:NSDayCalendarUnit|NSHourCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit
fromDate:dateA
toDate:dateB
options:0]; //Get day and hour
return components;
}
// Call method like
NSDateComponents *difference = [self getDateDifference:marriageDate];
NSLog(#"diff year = %f",difference.year);

How to calculate NSDate between two NSDate in 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;

Resources