Get the difference time between two NSString in Objective C - ios

I have two strings coming from my server in which I store the time, and I need to compare the time interval between those two, in minutes, and if it's necessary, in hours. Should I convert to NSDate or use NSString?
The NSStrings look like:
NOW 14:22
LAST TIME 10:18
EDIT #1
Since everyone is saying me to use NSDate, i converted the data in my database to DATETIME, and now i can compare the two NSDate using the following code :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"pt_BR"]];
[dateFormatter setDateFormat: #"yyyy-MM-dd HH:mm:ss"];
NSDate *currentDateTimeWithOffset = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone localTimeZone] secondsFromGMT]];
NSString *strDate = [dateFormatter stringFromDate:currentDateTimeWithOffset];
NSDate * now = [dateFormatter dateFromString:strDate];
NSDate *date = [dateFormatter dateFromString:#"2013-04-09 12:10:18"];
NSLog(#"Difference %f",[now timeIntervalSinceDate:date]);
And the result is the following :
Difference 864.000000
NOW 2013-04-09 15:24:42 +0000
LAST DATE 2013-04-09 12:10:18
Is that correct? the Difference is in Seconds?

If the format gets more complex than the one you've shown, consider using NSDateFormatter. For the simple example:
NSArray *hoursMins = [timeString componentsSeparatedByString:#":"];
NSInteger timeInMins = [hoursMins[0] intValue] * 60 + [hoursMins[1] intValue];
Then subtract the two times in minutes. The date formatter approach looks like this:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm"];
NSDate *date = [df dateFromString:timeString];
You can get a difference in seconds between two dates using:
[date timerIntervalSinceDate:anotherDate];

NSDateFormatter is the "clean" way to do it. But if you are looking for quick and dirty, and those are the actual strings you are getting (that include the NOW and LAST TIME), I'd just use a specific NSRange to pull the hours and minutes out and compare them.
Make sure, though that you check the hours, and if the "now" hour is before the "last time" hour, you add 24 to the now to throw in the day rollover.

With only NSString, NSDateFormatter is used to get NSDate
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
If you had separate values for hours, minutes and seconds you could use NSCalendar
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:1965];
[comps setMonth:1];
[comps setDay:6];
[comps setHour:14];
[comps setMinute:10];
[comps setSecond:0];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];
And a perfect solution would be to use timestamps instead of NSString. Not only it's easy to convert timestamps to NSDate (NSDate +dateWithTimeIntervalSinceReferenceDate)and then to NSString when needed, but you can also get the time difference by subtraction.
And with two NSDate objects the time difference is calculated with NSDate -timeIntervalSinceDate.

Related

Storing date and time separately in NSDate

So i am getting a string containing date and time in this format "2014-12-22T11:00:00+0500" Now in order to convert it into NSdate i am using
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate* date = [dateFormatter dateFromString:start_time];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString* temp = [dateFormatter stringFromDate:date];
self.eventDate = [dateFormatter dateFromString:temp];
NSDateFormatter* timeFormatter = [[NSDateFormatter alloc]init];
[timeFormatter setDateFormat:#"HH:mm:ss"];
NSString* temp2 = [timeFormatter stringFromDate:date];
self.start_time = [timeFormatter dateFromString:temp2];
Now even though the conversion is successful the problem is that eventDate also has has time after date 00:00:00. How can i remove this so that eventDate only contains date.
Conversly start_time has the time of event but also has some arbritrary reference date before that. How can i remove that so i only have time in start_time
I have searched hard and fast but haven't been able to figure out this problem. Any help would be appreciated.
You cannot remove either the date or the time to keep only one component. If I remember correctly NSDate object is internally just a number of seconds relative to a fixed point in time. So every NSDate contains the full date and time information.
What you probably want to do is to get the NSDateComponents you want from a NSDate object.
Instead of trying to store this separate, just display these dates separate. I think it could be useful sometimes to get the date completly, but i don't know your idea.
You can try with it, it may be help you.
NSString *finalDate = #"2014-12-22T11:00:00+0500";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate *date = [dateFormatter dateFromString:finalDate];
//For getting Time
NSDateFormatter* df1 = [[NSDateFormatter alloc]init];
[df1 setDateFormat:#"hh:mm:ss"];
NSString *time = [df1 stringFromDate:date];
NSLog(#"time %# ", time);
//For getting Date
NSDateFormatter* df2 = [[NSDateFormatter alloc]init];
[df2 setDateFormat:#"yyyy-MM-dd"];
NSString *actualDate = [df2 stringFromDate:date];
NSLog(#"actualDate %# ", actualDate);

NSDateFormatter not converting to correct date

I have a problem converting a string date to NSDate since the conversion is not correct. This is my code:
NSString *stringDate = #"6/20/2014 8:38:52 PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yyyy hh:mm:ss a"];
NSDate *timeStamp = [dateFormatter dateFromString:stringDate];
The log always says TIMESTAMP: 2014-06-20 12:38:37 +0000.
How can I convert it to a correct date? Thanks in advance.
I believe you are doing this to display the date in the log:
NSLog(#"timeStamp = %#", timeStamp);
Instead keep the date formatter around (store it globally or something) and do:
NSLog(#"timeStamp = %#", [dateFormatter stringFromDate:timeStamp]);
The difference is the first line of code calls [NSDate description] to format the date, which uses UTC/GMT time zone, where as the second line of code uses the time zone configured in the date formatter (which by default is the same the locale's time zone), and crucially the same time zone you used to parse the string in the first place.
Add
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
And you get date in UTC time zone.
You can use this. It will give you proper output
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[dateComponents setYear:2014];
[dateComponents setMonth:6];
[dateComponents setDay:20];
[dateComponents setHour:8];
[dateComponents setMinute:38];
[dateComponents setSecond:52];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [calendar dateFromComponents:dateComponents];
//NSDate *timeStamp = [dateFormatter dateFromString:stringDate];
NSLog(#"date = %#",date);
//solutions[2247:70b] date = 2014-06-20 08:38:52 +0000 printing date

Conversion of Seconds with NSDateFormatter Returns Null

I am trying to convert a string representing seconds into a string with hours minutes seconds format. Input might look like 305 seconds and I want it to show 5:05. Shouldn't I be able to do this using NSDateFormatter? I have tried several variations on the following, but the output is always null.
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"s"];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"hh:mm:ss"];
NSString *seconds = #"305";
NSDate *myDate = [inputFormatter dateFromString:seconds];
NSString *twelveHourTime = [outputFormatter stringFromDate:myDate];
NSLog(#"twelve hour time: %#", twelveHourTime);
I have looked at many of the other NSDate posts, and a lot of the issues are related to incorrect format. Best I can tell from the NSDate formatting guide a single lower case s is the correct input for seconds. That said, I also tried multiple lower case s and upper case S for input format and still did not get correct results.
I'd appreciate knowing what I'm doing wrong, or if this type of conversion is not meant to be done with NSDateFormatter. Thanks.
You can use NSDateComponents to achieve this:
NSString *seconds = #"305";
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"HH:mm:ss"];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.second = [seconds integerValue];
NSDate *date = [[NSCalendar autoupdatingCurrentCalendar] dateFromComponents:dateComponents];
NSLog(#"twelve hour time: %#", [outputFormatter stringFromDate:date]);

Date and Time issue in ios [duplicate]

This question already has answers here:
NSDate is not returning my local Time zone /default time zone of device
(7 answers)
Closed 9 years ago.
I am using the datepicker for picking the time but after sending to the server when I am retrieving back then its showing 5-6 hour difference.
Server hosted in USA.
So how I will do it accurately without any difference, User do request from any where.
Thanks,
Arun
UTC is standard time zone to be used. Following is the code to get date in UTC
+(NSString *)getCurrentTime{
NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-ddHH:mm:ss"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
NSString *dateStr = [dateFormat stringFromDate:date];
RELEASE_OBJECT(date)
RELEASE_OBJECT(dateFormat)
return dateStr;
}
Send the date with the timezone. For example:
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSDate *date = [formatter dateFromString:dateString];
Will include the timezone and the server will be able to translate to its own timezone.
We use the ISO 8601 for better compatibility. There are also NSFormatter subclasses that to convert from ISO 8601 to NSDate and back (like this).
It is time zone issue. You can use [yourDate dateByAddingInterval:[NSTimeZone secondsFromGMT]]; .
Please try to set the Locale for the time:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd MM yyyy hh:mm:ss"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"] autorelease]];
NSDate* sourceDate = [dateFormatter dateFromString:dateString];
//Timezones
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
//Interval in Timezones
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
//converted date
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] ;
NSString *strFinalDate = [dateFormatter stringFromDate:destinationDate];
[dateFormatter release];
[destinationDate release];
If you are sending your iPhone default times to server and server is also sending the same time which you have send it then it will be problem of the converting your NSDate to NSString with NSDateFormatter with some different timezone.
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
Use above code when you using NSDateFormatter.

How to get the correct date by using dateformatter method?

here is my code:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:1275822000000+0000];
// the string is json parsing string
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(#"formattedDateString: %#", formattedDateString);
The output is Dec 20,5828963
But my required output is June 6,2010
How to change my code for correct output?
If you want to receive June 6, 2010 from some magic number then use this:
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:297475822];
For some reason your number is very big, and as #wrock mentioned it multiplies on 10 million, so for getting correct value you can use dateWithTimeIntervalSince1970 and divide it on 10 million
NSDate *date = [NSDate dateWithTimeIntervalSince1970:1275822000];
First: your timestamp seems like a Java timestamp, but it has a few extra zeros (4 of them exactly). You have to convert this to a Unix timestamp, which is the number of seconds since the Unix epoch (as opposed to Java, which is the number of milliseconds since the Unix epoch).
dateWithTimeIntervalSinceReferenceDate: doesn't accept Unix timestamps, but the conversion is easy:
double timestampFromService = 12758220000000000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:
(timestampFromService*1.0e-7)];
Use date in readable manner :
NSDate *myDate = [NSDate dateWithString:#"2010-06-06 00:00:00"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString *formattedDateString = [dateFormatter stringFromDate:myDate];
NSLog(#"formattedDateString: %#", formattedDateString);

Resources