Find different between hours - ios

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"]);

Related

How to get time interval for every 30:00(30 minutes) from current time to 10:30 pm

Need help to show the time intervals for every 30 mins, suppose the current time is 11:45 am then
Time intervals should be : 12:00 pm,12:30 pm,01:00 pm,01:30 pm,02:00 pm,02:30 pm......10:30 pm.
NSString *time = #"10.30 pm";
NSDate *date1;
NSDate *date2;
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh.mm a"];
date1 = [formatter dateFromString:time];
date2 = [formatter dateFromString:[formatter stringFromDate:[NSDate date]]];
}
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));
This code returns me difference of current time and the given time how can I proceed further.
You can do something like,
NSString *startTime = #"02:00 AM";
NSString *endTime = #"11:00 AM";
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"hh:mm a"];
NSDate* fromTime = [timeFormat dateFromString:startTime];
NSDate* toTime = [timeFormat dateFromString:endTime];
NSDate *dateByAddingThirtyMinute ;
NSTimeInterval timeinterval = [toTime timeIntervalSinceDate:fromTime];
NSLog(#"time Int %f",timeinterval/3600);
float numberOfIntervals = timeinterval/3600;
NSLog(#"Start time %f",numberOfIntervals);
for(int iCount = 0;iCount < numberOfIntervals*2 ;iCount ++)
{
dateByAddingThirtyMinute = [fromTime dateByAddingTimeInterval:1800];
fromTime = dateByAddingThirtyMinute;
NSString *formattedDateString;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm a"];
formattedDateString = [dateFormatter stringFromDate:dateByAddingThirtyMinute];
NSLog(#"Time after 30 min %#",formattedDateString);
}
In for loop I have taken numberOfIntervals*2 because time interval is 30 min, so 60/30 = 2 and your datebyAddingThirtyMinute is 1800 because 30 min = 1800 seconds. If you want time after every 10 minutes then it should 60/10 = 6, so it should numberOfIntervals*6. And your datebyAddingThirtyMinute should be [fromTime dateByAddingTimeInterval:600];
Hope this will help :)
The most reliable way (also to consider daylight saving time changes) is to use the date math capabilities of NSCalendar.
Simply adding seconds with dateByAddingTimeInterval is not recommended at all.
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
// get minute and hour from now
NSDateComponents *nowComponents = [cal components:NSCalendarUnitHour | NSCalendarUnitMinute fromDate: now];
NSDate *currentDate;
// if current minutes is not exactly 0 or 30 get back to the past half hour
if (nowComponents.minute % 30 != 0) {
NSInteger pastHalfHourIndex = nowComponents.minute / 30;
nowComponents.minute = pastHalfHourIndex * 30;
currentDate = [cal nextDateAfterDate:now matchingHour: nowComponents.hour minute: nowComponents.minute second: 0 options: NSCalendarMatchNextTime | NSCalendarSearchBackwards];
} else {
currentDate = now;
}
NSMutableArray<NSDate *>* dates = [NSMutableArray array];
// loop and add 30 minutes until the end time (10:30 pm) is reached
while (nowComponents.minute != 30 || nowComponents.hour != 22) {
currentDate = [cal dateByAddingUnit:NSCalendarUnitMinute value: 30 toDate: currentDate options: NSCalendarMatchNextTime];
[dates addObject:currentDate];
nowComponents = [cal components:NSCalendarUnitHour | NSCalendarUnitMinute fromDate: currentDate];
}
NSLog(#"%#", dates);
Try this code it works for you
NSDateFormatter *datefrmt = [[NSDateFormatter alloc] init];
[datefrmt setDateFormat:#"hh:mm a"];
NSDate* startingTime = [datefrmt dateFromString:startTime];
NSDate* endingTime = [datefrmt dateFromString:endTime];
NSLog(#"Starting time is %#", startingTime);
NSLog(#"Stop time is %#", endingTime);
NSDate * addingTimeInterval;
addingTimeInterval = [startingTime dateByAddingTimeInterval:1800];
NSLog(#"Required output is %#", addingTimeInterval);
I would first check if the given start time is AM or PM, after doing that, I would find the nearest (rounded up) 30m interval of time and simply add 30m to it and check whether or not I was at the given stop stop time, and if not increment a counter.
You could also add each 30m interval to a list if you wanted to keep track of and return that list to be printed out.
If you get the Start date is current date and time, then the end date is automatically set 30 mins use dateByAddingTimeInterval:, see my example,
NSDate *startDate = [NSDate date];
then set ending date is below code,
currentdate = startDate; //today
endingDate = [startDate dateByAddingTimeInterval:(60*60)/2]; // 60*60 is 1 hour.
this above method automatically calculate current time to end time add 30 minutes.
hope its helpful

calculate time interval of format hh.mm.ss in iOS

I have date in format hh.mm.ss , now i want difference between two time of current format in hours. How can this be done.
NSString *time1 = #"12.43.42";
NSString *time2 = #"07.54.43";
I want time in hours.
please follow like this
NSDateFormatter *df = [NSDateFormatter new];
df.dateFormat = #"hh.mm.ss";
NSDate *date1 = [df dateFromString:#"12.43.42"];
NSDate *date2 = [df dateFromString:#"07.54.43"];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfHours = secondsBetween / (60 * 60);

timeIntervalSinceDate not returning correct answer objective c

I'm trying to get timeIntervalSinceDate to send a log in secs of how much time has elapsed since a previous date but it isn't working. I set it for 1 minute in the future each time I test it but I not get logs that correspond like the latest log was this: 2015-09-22 16:30:04.469 Wakey Wakey[49785:7077539] Seconds nan 2015-09-22 16:30:04.470. This is the code:
NSString *dateTimeString = [dateFormatter stringFromDate: dateTimePicker.date ];
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd:MM:YYYY:ss:mm:hh"];
NSDate *dateTimeSeconds = [[NSDate alloc] init];
dateTimeSeconds = [dateFormatter1 dateFromString:dateTimeString];
NSTimeInterval secs = [currentTime timeIntervalSinceDate:dateTimeSeconds];
NSLog(#"Seconds %g", secs);
What should I do to fix it?
Why bother with NSDateFormatter. Try
NSTimeInterval seconds = [[NSDate date] timeIntervalSinceDate:dateTimePicker.date];
NSLog(#"seconds %.f", seconds);
Also use %.f instead of %g on the NSLog
Try with this
NSDate* date1 = someDate;
NSDate* date2 = someOtherDate;
NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
Please try with below date format
kTimeStampFormat #"dd-MM-yyyy'T'HH:mm:ss.SSS'Z'"
Use UTC format for consistency

Convert date to timestamp in iOS

How do you convert any given date to milliseconds? For example, 2014-01-23 to timestamp conversion.
NSDate *date = [dateFormatter dateFromString:#"2014-01-23"];
NSLog(#"date=%#",date);
NSTimeInterval interval = [date timeIntervalSince1970];
NSLog(#"interval=%f",interval);
NSDate *methodStart = [NSDate dateWithTimeIntervalSince1970:interval];
[dateFormatter setDateFormat:#"yyyy/mm/dd "];
NSLog(#"result: %#", [dateFormatter stringFromDate:methodStart]);
Output result: 1970/30/01
Swift
Convert the current date/time to a timestamp:
// current date and time
let someDate = Date()
// time interval since 1970
let myTimeStamp = someDate.timeIntervalSince1970
See also
Convert Date to Integer in Swift
Creating a Date and Time in Swift
How to get the current time as datetime
Have it a try. "mm" stands for minute while "MM" stands for month.
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init] ;
[dateFormatter setDateFormat:#"yyyy-MM-dd"] ;
NSDate *date = [dateFormatter dateFromString:#"2014-01-23"] ;
NSLog(#"date=%#",date) ;
NSTimeInterval interval = [date timeIntervalSince1970] ;
NSLog(#"interval=%f",interval) ;
NSDate *methodStart = [NSDate dateWithTimeIntervalSince1970:interval] ;
[dateFormatter setDateFormat:#"yyyy/MM/dd "] ;
NSLog(#"result: %#", [dateFormatter stringFromDate:methodStart]) ;
NSTimeinterval is really a double, being seconds since a particular date (in your case, the start of 1970)
NOTE :- UNIX Timestamp format contains 13 Digits so we need a 1000 multiplication with the result.
And the timestamp must be UTC ZONE not our local Time Zone.
- (void)GetCurrentTimeStamp
{
NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
[objDateformat setDateFormat:#"yyyy-MM-dd"];
NSString *strUTCTime = [self GetUTCDateTimeFromLocalTime:#"2014-01-23"];
NSDate *objUTCDate = [objDateformat dateFromString:strUTCTime];
long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);
NSLog(#"Local Time = %#---- UTC = %# ----- TimeSatmp = %ld ---- TimeStamp = %lld",strTime,strUTCTime,unixTime,milliseconds);
}
- (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *objDate = [dateFormatter dateFromString:IN_strLocalTime];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
NSString *strDateTime = [dateFormatter stringFromDate:objDate];
return strDateTime;
}
[date1 timeIntervalSinceDate:date2] will return seconds from two NSDate objects.
double seconds = [date1 timeIntervalSinceDate:date2];
double milliSecondsPartOfCurrentSecond = seconds - [seconds intValue];
milliSecondsPartOfCurrentSecond

double converted to hours minutes and seconds with NSdateformatter returning wrong answer

i am using the following code to convert a value of 18900 into hh:mm:ss
unfortunately the value returned doesn't seem right as it gives me 06:15:00
can anyone please advise why its going wrong
thanks
-(NSString*)setHours:(double)result
{
NSLog(#"result %0.2f",result);
NSDate *date = [NSDate dateWithTimeIntervalSince1970:result];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm:ss"];
NSString *localizedString = [formatter stringFromDate:date];
[formatter release];
return localizedString;
}
Since you have a value that is the number of seconds since midnight, you don't need a date formatter. Try this:
-(NSString*)setHours:(double)result {
int secs = result;
int h = secs / 3600;
int m = secs / 60 % 60;
int s = secs % 60;
NSString *text = [NSString stringWithFormat:#"%02d:%02d:%02d", h, m, s];
}
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
First of all, you have to convert miliseconds in to seconds by dividing miliseconds by 1000.
NSTimeInterval result= 18900/1000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:result];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSString *formattedDate=[formatter stringFromDate:date];
NSLog(#"Formatted Date : %#",formattedDate);
It's giving you a result for your current time zone, and the time is specified in UTC. So you're an hour after GMT I suppose.
Check out this question: NSDate dateWithTimeIntervalSince1970 NOT returning GMT/UTC time

Resources