obj-c : iphone programming NSTimeInterval problem - objective-c

i got a problem with my time interval. I need to get the interval of two times in this format : HH:MM. If i enter : 15:35 and 16:35 it is ok, but when i do 20:30 to 01:30, it gives me like 18 hours interval.. anyone have an idea?
NSString *startDate= starthere.text;
NSString *endDate = endhere.text;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
NSDate *dateSelected = [dateFormatter dateFromString:startDate];
NSDate *dateSelected2 = [dateFormatter dateFromString:endDate];
[dateFormatter release];
if ([dateSelected2 earlierDate:dateSelected] == dateSelected2)
{
dateSelected2 = [dateSelected2 dateByAddingTimeInterval:86400];
}
interval = [dateSelected2 timeIntervalSinceDate:dateSelected];

Your end date is before your start date, so there are 19 hours between them. A quick fix might be to add 24 hours to your end date if it compares as earlier than the start date. Something like:
if ([dateSelected2 earlierDate:dateSelected] == dateSelected2)
{
dateSelected2 = [dateSelected2 dateByAddingTimeInterval:86400];
}
The NSDate documentation has everything you need to know.

Related

How can I handle this European-style timestamp?

I’m trying to check through thousands of lines in video subtitle files (in .srt format) and searched the internet for days on end for a solution, but to no avail. The subs contain in/out timestamps as shown in the following example:
61
00:08:35,504 --> 00:08:38,629
Do you know where he left the car keys?
in hours, minutes, seconds and milliseconds (notice the European-style comma before the millisecond part, representing the decimal point). What I plan to do is parse the timestamp into its two components and check the difference between them, since many are faulty. I built a simple test function to handle the plain hh:mm:ss part which works well:
-(IBAction)checkSubLength:(id)sender
{
NSString *inStr = #"10:10:45";
NSString *outStr = #"10:20:57";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm:ss"];
NSDate *inTime = [dateFormatter dateFromString:inStr];
NSDate *outTime = [dateFormatter dateFromString:outStr];
NSTimeInterval distanceBetweenDates = [outTime timeIntervalSinceDate:inTime];
NSLog(#"time difference:%.3f", distanceBetweenDates);
}
However, I just can’t get the fractional part to display no matter what I try. How can I modify/change my code do that? Any help much appreciated.
You need to specify the millis in the format string:
NSString *inStr = #"10:10:45,111";
NSString *outStr = #"10:20:57,222";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm:ss,SSS"];
NSDate *inTime = [dateFormatter dateFromString:inStr];
NSDate *outTime = [dateFormatter dateFromString:outStr];
NSTimeInterval distanceBetweenDates = [outTime timeIntervalSinceDate:inTime];
NSLog(#"time difference:%.3f", distanceBetweenDates);
which then prints
time difference:612.111
as expected

Issue while parsing timestamp into date and time using Objective-C

I am getting timestamp for server in stringFormat which is in miliseconds.
I have to convert it in date and time and display to the user.
I have done it using following code:
+ (NSString *)getDateAndMonthFromTimeStamp:(NSString*)timestampString
{
NSTimeInterval timeStamp = [timestampString integerValue]/1000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
[dateFormatter setDateFormat:#"dd MMM"];
NSString *dateNmonth = [[dateFormatter stringFromDate:date]uppercaseString];
return dateNmonth;
}
When I run it in iPhone6 it works fine. But when I run it in iPhone 5 and iPhone5s it shows me unwanted date.
I debug the code and found this:
timestampString = #"1459498716000"
NSTimeInterval timeStamp = [timestampString integerValue]/1000;
//after this timeStamp becomes:
timeStamp = 2147483;
and then my date becomes 1970-01-25 20:31:23 +0000
I am in doubt that NSTimeinterval is overflowed with data. is this right?
How can I fix this.
try this code
NSString* takeOffTime = #"1396614600000";
double miliSec = takeOffTime.doubleValue;
NSDate* takeOffDate = [NSDate dateWithTimeIntervalSince1970:miliSec/1000];

Different NSDate for same timestapm on ios versions (ios 6 and iOS7)

I ran into this weird issue where one of the method in my code is returning different dates for same timestamp value in different ios version.
Following is the code for that method.
+(NSDate *)getDateFromTheTimeStampAsDate:(NSInteger)timeStamp
{
NSLog(#"Timestamp - %d",timeStamp);
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setLocale:usLocale];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"PST"]];
[dateFormatter setDateFormat:#"MMM DD,yyyy"];
return [dateFormatter dateFromString:[dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeStamp]]];
}
For timestamp = 1361581013 following are the NSDates values returned from above function:
iOS6 - 2013/02/01
iOS7 - 2013/02/22
Is there anything wrong with this code ?
Update: I forgot to look at the date format, earlier. Thanks to one of the comment I managed to get correct date. This was a part of legacy code so in the decided to just trash it and use following:
[NSDate dateWithTimeIntervalSince1970:timeStamp];
First the output isn't ever close to the date. On the terminal try date -r 1361581013. At least then you can see if you are getting close.
Second, convert the timestamp to an NSDate. Log that see if its close.
NSDate *d = [NSDate dateWithTimeIntervalSince1970:1361581013] ;
NSLog(#"d = %#" , d) ;
Third after you know you are getting the NSDate then apply formats to it.
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterLongStyle;
df.timeStyle = NSDateFormatterLongStyle;
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"PST" ];
NSLog(#"d with formatting 1 = %#" , [df stringFromDate:d]) ;
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"EST" ];
NSLog(#"d with formatting 1 = %#" , [df stringFromDate:d]) ;
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT" ];
NSLog(#"d with formatting 1 = %#" , [df stringFromDate:d]) ;
Then you will know you got it right.
d = 2013-02-23 00:56:53 +0000
d with formatting 1 = February 22, 2013 at 4:56:53 PM PST
d with formatting 1 = February 22, 2013 at 7:56:53 PM EST
d with formatting 1 = February 23, 2013 at 12:56:53 AM GMT

current Date and Time - NSDate

I need to display the current Date and Time.
I have used ;
NSDate *currentDateNTime = [NSDate date];
I want to have the current date and time (Should display the system time and not GMT time).
The output should be in a NSDate format and not NSString.
for example;
NSDate *currentDateNTime = [NSDate date];
// Do the processing....
NSDate *nowDateAndTime = .....; // Output should be a NSDate and not a NSString
Since all NSDate is GMT referred, you probably want this:
(don'f forget that the nowDate won't be the actual current system date-time, but it's "shifted", so if you will generate NSString using NSDateFormatter, you will see a wrong date)
NSDate* currentDate = [NSDate date];
NSTimeZone* currentTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* nowTimeZone = [NSTimeZone systemTimeZone];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:currentDate];
NSInteger nowGMTOffset = [nowTimeZone secondsFromGMTForDate:currentDate];
NSTimeInterval interval = nowGMTOffset - currentGMTOffset;
NSDate* nowDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:currentDate];
Every moment in time is the same moment in time everywhere around the world —- it is just expressed as different clock times in different timezones. Therefore, you can't change the date to some other date that represents the time in your timezone; you must use an NSDateFormatter that you feed with the timezone you are in. The resulting string is the moment in time expressed in the clock time of your position.
Do all needed calculations in GMT, and just use a formatter for displaying.
Worth reading
Does [NSDate date] return the local date and time?
Some useful resources for anyone coming to this more recently:
Apple date and time programming guide do read it if you're doing anything serious with dates and times.
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html#//apple_ref/doc/uid/10000039i?language=objc
Useful category on NSDate with lots of utilities does allow a ~new~ date to be generated based on an existing date.
https://github.com/erica/NSDate-Extensions
There's also a swift version of the category
https://github.com/erica/SwiftDates
You need an NSDateFormatter and call stringFromDate this method to get a string of your date.
NSDateFormatter *dateformater = [[NSDateFormatter alloc] init];
[dateformater setDateFormat:#"yyyyMMdd,HH:mm"];
NSString *str = [dateformater stringFromDate: currentDateNTime];
use this method
-(NSDate *)convertDateToDate:(NSDate *) date
{
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[formatter setDateFormat:#"yyyy-MM-d H:m:s"];
NSString * strdate = [formatter stringFromDate:date];
nowDate = [formatter dateFromString:strdate];
return nowDate;
}
this may return you what you want.
i hope you this may help you.

Formatting seconds into hh:ii:ss

I have app that is a basic timer. It tracks the number of seconds the app has run. I want to convert it so the seconds (NSUInteger) are displayed like: 00:00:12 (hh:mm:ss). So I've read this post:
NSNumber of seconds to Hours, minutes, seconds
From which I wrote this code:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[self meeting] elapsedSeconds]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm:ss"];
It works fine, but it starts out with 04:00:00. I'm not sure why. I also tried doing something like:
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:[[self meeting] elapsedSeconds] * -1];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm:ss"];
Thinking that it would display the counter correctly, but it does a wierd 01:23:00, then just flops to 04:00:00 and stays there for the rest of the time.
MS
This is similar to a previous answer about formatting time but doesn't require a date formatter because we aren't dealing with dates any more.
If you have the number of seconds stored as an integer, you can work out the individual time components yourself:
NSUInteger h = elapsedSeconds / 3600;
NSUInteger m = (elapsedSeconds / 60) % 60;
NSUInteger s = elapsedSeconds % 60;
NSString *formattedTime = [NSString stringWithFormat:#"%u:%02u:%02u", h, m, s];
While there are easier ways of doing this (#dreamlax has a very good way), let me explain what is wrong with your example and let's get it working:
First, the reason that it is showing 04:00:00 (well, it is probably actually showing 04:00:12) is because it is converting the time from UTC/GMT to your local time. To fix this, you need to add the following line:
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
Then, it will no longer show 04:00:12 because it doesn't convert the timezone. Unfortunately, it will now show 12:00:12 instead of 00:00:12 because it is midnight. In order to fix that, have it convert the string to 24 hour time instead by using the HH formatter instead of hh:
[formatter setDateFormat:#"HH:mm:ss"];
Keep in mind that since this was designed to work with times, that it will not work for more than 24 hours (because it will "roll over" to midnight again).
The full code would be:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[self meeting] elapsedSeconds]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSLog(#"%#", [formatter stringFromDate:date]);
// Results: 00:00:12