How to calculate the total of traveled time - ios

I need to get a NSString that displays a total of traveled time using 2 NSStrings
I have
NSString *origin = [NSString stringWithFormat:#"5:30"];
NSString *destiny = [NSString stringWithFormat:#"6:00"];
The problem is I don't know how to format this NSStrings to NSDate and do destiny - origin so the output would be a new NSString that says 30 minutes
EDIT: I've just investigate a little about the NSDateFormatter but if I use it:
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
NSDate * mydate = [dateFormatter dateFromString:origin];
NSDate returns me a nil Is there something wrong?
Any help will be very appreciated.

NSString *origin = #"5:30";
NSString *destiny = #"6:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"H:mm"];
NSDate *originDate = [dateFormatter dateFromString:origin];
NSDate *destinyDate = [dateFormatter dateFromString:destiny];
NSTimeInterval interval = [destinyDate timeIntervalSinceDate:originDate];
NSDate *intervalDate = [NSDate dateWithTimeInterval:interval sinceDate:originDate ];
NSDateComponents *comps =[[NSCalendar currentCalendar] components:NSMinuteCalendarUnit
fromDate:originDate
toDate:intervalDate
options:0];
Now the NSDateComponents will hold the difference in minutes
NSLog(#"%ld", [comps minute]);
will log 30
If you would like the hours and minutes, you can do
NSString *origin = #"5:30";
NSString *destiny = #"7:00";
// ....
NSDateComponents *comps =[[NSCalendar currentCalendar] components: (NSMinuteCalendarUnit|NSHourCalendarUnit)
fromDate:originDate
toDate:intervalDate
options:0];
Now comps will hold the 90 minutes as 1 hour and 30 minutes.
NSLog(#"%ld %ld", [comps hour],[comps minute]);
logs 1 30

NSString *origin = #"5:30";
NSString *destiny = #"6:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"H:mm"];
NSDate *originDate = [dateFormatter dateFromString:origin];
NSDate *destinyDate = [dateFormatter dateFromString:destiny];
NSTimeInterval diffInSeconds = [destinyDate timeIntervalSinceDate:originDate];
NSTimeInterval diffInMinutes = diffInSeconds / 60;
NSString *minutesString = [NSString stringWithFormat:#"%0.0f", diffInMinutes];

Related

Convert NSSting to NSDate

I have string 2015-08-10T12:00 how can I convert it to Date?
My code did not works
[self.dataFormatter setDateFormat:#"yyyy-MM-ddTHH:mm"];
NSDate *date = [self.dataFormatter dateFromString:dateStg];
Use this date format:
yyyy-MM-dd'T'HH:mm
converted current Date into String
//Get Current Date
NSLocale *en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
assert(en_US_POSIX != nil);
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:en_US_POSIX];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
Converted Current Time inTo NSString
//Get Current Date
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *dateComponents = [gregorian components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:now];
NSInteger hour = [dateComponents hour];
NSString *am_OR_pm=#"AM";
if (hour>12){
hour=hour%12;
am_OR_pm = #"PM";
}
NSInteger minute = [dateComponents minute];
NSString *strTime=[NSString stringWithFormat:#"%02d:%02d %#", hour, minute ,am_OR_pm];
Converted 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];

how to find out what day is a date in iOS [duplicate]

I have a webservice that returns the date in this format:
2013-04-14
How do i figure out what day this corresponds to?
This code will take your string, convert it to an NSDate object and extract both the number of the day (14) and the name of the day (Sunday)
NSString *myDateString = #"2013-04-14";
// Convert the string to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:myDateString];
// Extract the day number (14)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];
// Extract the day name (Sunday)
dateFormatter.dateFormat = #"EEEE";
NSString *dayName = [dateFormatter stringFromDate:date];
// Print
NSLog(#"Day: %d: Name: %#", day, dayName);
Note: This code is for ARC. If MRC, add [dateFormatter release] at the end.
An alternate method for getting the weekday can be:
NSString *myDateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:myDateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = [components weekday];
NSString *weekdayName = [dateFormatter weekdaySymbols][weekday - 1];
NSLog(#"%# is a %#", myDateString, weekdayName);
You can use this code it working for me.
NSString *dateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"%#", [dateFormatter stringFromDate:dateFromString]);
If you have 2013-04-14 stored in a NSString called date, then you can do this...
NSArray *dateComponents = [date componentsSeperatedByString:#"-"];
NSString *day = [dateComponents lastObject];
Swift 3:
let datFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
Bonus: If you want to set your own date template instead of using Date() above:
let datFormat = DateFormatter()
datFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let thisDate = datFormat.date(from: "2016-10-13T18:00:00-0400")
Then call the 1st code after this.

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

Trying to use NSDate for time only

I'm struggling to find a way to use NSDate for time only purposes.
I was trying to do the following code:
- (void)awakeFromInsert
{
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.minute = 45;
comps.second = 0;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
self.periodDuration = [calendar dateFromComponents:comps];
NSLog(#"periodDuration: %#",self.periodDuration);
comps = [[NSDateComponents alloc] init];
comps.hour = 8;
comps.minute = 0;
self.firstPeriodStartTime = [calendar dateFromComponents:comps];
NSLog(#"firstPeriodTime: %#",self.periodDuration);
}
But the result I get is:
periodDuration: 0001-12-31 22:24:04 +0000
firstPeriodTime: 0001-12-31 22:24:04 +0000
The result I was expecting:
periodDuration: 45:00
firstPeriodTime: 08:00
What am I doing wrong? How can I fix this?
Thank you.
The log of date is misleading you, if you are forming a date with only a few components you will not get a proper date instance which uniquely identifies a date and time.
If you try with this code snipped you can find that if you are just converting the dates back to string it is just as you expect
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.minute = 45;
comps.second = 0;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *periodDate = [calendar dateFromComponents:comps];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm:ss"];
NSLog(#"periodDuration: %#",[dateFormatter stringFromDate:periodDate]);
comps = [[NSDateComponents alloc] init];
comps.hour = 8;
comps.minute = 0;
NSDate *firstPeriodDate = [calendar dateFromComponents:comps];
[dateFormatter setDateFormat:#"HH:mm"];
NSLog(#"firstPeriodTime: %#",[dateFormatter stringFromDate:firstPeriodDate]);
periodDuration: 45:00
firstPeriodTime: 08:00
You can use NSDateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
NSLog(#"%#",[dateFormatter stringFromDate:[NSDate date]]);
Use a NSTimeInterval (which is, basically, a double containing the number of seconds). To store it in CoreData:
[NSNumber numberWithDouble:myTimeInterval];
As for formatting: If you want more than 24h displayed, use this:
NSUInteger seconds = (NSUInteger)round(myTimeInterval);
NSString *formattedDate = [NSString stringWithFormat:#"%02u:%02u:%02u",
seconds / 3600, (seconds / 60) % 60, seconds % 60];
NSLog(#"%#", formattedDate);
If you don't want more than 24h, you can use NSDate and NSDateFormatter again:
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:myTimeInterval];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
NSString *formattedDate = [dateFormatter stringFromDate:date];
NSLog(#"%#", formattedDate);
NSString *timeString;
timeString = [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterNoStyle
timeStyle:NSDateFormatterMediumStyle];
12:03:54 PM

How do I take a date and extract the day in iOS"

I have a webservice that returns the date in this format:
2013-04-14
How do i figure out what day this corresponds to?
This code will take your string, convert it to an NSDate object and extract both the number of the day (14) and the name of the day (Sunday)
NSString *myDateString = #"2013-04-14";
// Convert the string to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:myDateString];
// Extract the day number (14)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];
// Extract the day name (Sunday)
dateFormatter.dateFormat = #"EEEE";
NSString *dayName = [dateFormatter stringFromDate:date];
// Print
NSLog(#"Day: %d: Name: %#", day, dayName);
Note: This code is for ARC. If MRC, add [dateFormatter release] at the end.
An alternate method for getting the weekday can be:
NSString *myDateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:myDateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = [components weekday];
NSString *weekdayName = [dateFormatter weekdaySymbols][weekday - 1];
NSLog(#"%# is a %#", myDateString, weekdayName);
You can use this code it working for me.
NSString *dateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"%#", [dateFormatter stringFromDate:dateFromString]);
If you have 2013-04-14 stored in a NSString called date, then you can do this...
NSArray *dateComponents = [date componentsSeperatedByString:#"-"];
NSString *day = [dateComponents lastObject];
Swift 3:
let datFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
Bonus: If you want to set your own date template instead of using Date() above:
let datFormat = DateFormatter()
datFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let thisDate = datFormat.date(from: "2016-10-13T18:00:00-0400")
Then call the 1st code after this.

Resources