Problem in getting proper time - iphone

i am not able to get proper time from a given time.
My code is as follows
NSArray * array_TimeSlotWith_StartDate = [ #"01/05/2010 10:15:33" componentsSeparatedByString:#" "];
NSArray * array_TimeSlotWith_EndDate = [ #"01/05/2010 10:45:43" componentsSeparatedByString:#" "];
NSLog(#" array_TimeSlotWith_StartDate === %#",array_TimeSlotWith_StartDate);
NSLog(#"array_TimeSlotWith_EndDate == %#",array_TimeSlotWith_EndDate);
NSArray * Array_StartTime = [[array_TimeSlotWith_StartDate objectAtIndex:1] componentsSeparatedByString:#":"];
NSLog(#"Array_StartTime == %#",Array_StartTime);
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:#"HH:mm:ss"];
NSDate *date1 = [df dateFromString:[array_TimeSlotWith_StartDate objectAtIndex:1]];
NSDate *date2 = [df dateFromString:[array_TimeSlotWith_EndDate objectAtIndex:1]];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
NSLog(#"date 1%#",date1);
NSLog(#"date 2%#",date2);
It gives me value of date 1 as 1970-01-01 04:45:33 +0000 instead of this what i need is just the time an that should be 10:15:33.
And same for the end date also it gives log as 1970-01-01 05:15:43 +0000 instead of this it should output as only the time component with value 10:45:43 .

Time doesn't exist without a date. If you don't specify any date, the date formatter will default to "1970-01-01"(Unix epoch). I hope this SO link will help you.
Though the date1 and date2 don't contain the value you've expected, I feel that, interval should contain the correct result you need. I suggest you to just ignore the dates in this context.

you neither specifying the date and timezone that's the reason NSDate object pick the default one for its use.

Related

Time difference between two times in iPhone

I have two times :
10:23:51
10:31:54
Both values are stored as strings in a SQLite database.
I want to find the difference between these two times in hh:mm format.
How can I do this?
I have searched a lot. But can't find a proper solution.
Help me out.
Thanks.
Edit :
See basically I am having two arrays:
InTimeArray and OuttimeArray.
Now in the viewDidload method , I am fetching all the intime entries in the IntimeArray and Outtime entries in the outtime Arrays.
Now I am passing one by one values in tableview like in 1st row
IntimeArray[0]
OuyTimeArray[0]
second row:
IntimeArray[1]
OuyTimeArray[1]
Now I want to count the differences between 1st row's intime and outtime in HH:MM format.
I am really confused.
you can take a look at that :
-(NSDate *)dateFromString:(NSString *)string
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormat setLocale:locale];
[dateFormat setDateFormat:#"HH:mm:ss"];
NSDate *date1 = [dateFormat dateFromString:string];
if(!date1) date1= [NSDate date];
[dateFormat release];
[locale release];
return date1;
}
this will turn the NSDate to you and when you change them both to NSDates then you can learn the difference by looking at this.
i hope this will help you..
You have to first change your both strings into date format using this method :-
- (NSDate *)dateFromString:(NSString *)string;
after that you just have to calculate number of seconds between both the dates.Thats it.
OR there is another simple way to do this. i.e.
get dates from both arrays first like this:-
NSDate *eventStartDate = [IntimeArray objectAtIndex:indexpath.row];
NSDate *eventEndDate = [OuyTimeArray objectAtIndex:indexpath.row];
Then calculate difference between both the dates like this :-
NSTimeInterval startTimeInterval = [eventStartDate timeIntervalSinceDate:currentDate];
Hope it helps Thanks :)
Try this:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *d1 = [formatter dateFromString:IntimeArray[0]];
NSDate *d2 = [formatter dateFromString:OuyTimeArray[0]];
NSTimeInterval ti = [d2 timeIntervalSinceDate:d1];
float hours = floor(ti / 3600);
float minutes = floor((ti - hours*3600) / 60);
NSString *s = [NSString stringWithFormat:#"%02.0f:%02.0f",hours,minutes];
For your given example, NSLog(#"Time passed: %#",s); will print 00:08.

iPhone - Strange problem with NSDate, NSString, and Timezones

I've searched and haven't found an exact question like mine, so here goes nothing:
I have a NSString containing a key that I pull from an XML feed. The key is a time in 24-hour format (e.g. 13:30 or 15:00.) I'd like to convert the NSString to an NSDate and have it converted to the appropriate timezone based on the device's set timezone. The key is Unicode HH:mm (24:00), so I'm curious why this does not work as it should.
I've already gotten a basic outline that should work, but alas does not. The 2nd NSLog (Got NS Date) returns null and the final log returns a strange number (1969-12--2147483629 -596:-31:-23 +0000 to be precise.) What am I doing wrong here?
Thanks in advance,
NSString *dateString = [dict objectForKey:#"24hrdate"];
NSLog(#"NSString Date: %#", dateString);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm"];
NSDate *sourceDate = [formatter dateFromString:dateString];
NSLog(#"Got NS Date: %#", sourceDate);
NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone *destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
NSLog(#"Final Date: %#", destinationDate);
First of all understand that the date component will be 01-01-1970 because it isn't provided. I am assuming that you want the time to be 04:00 GMT if the input string is #"04:00". That you can achieve by setting the time zone of the formatter.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
[formatter setDateFormat:#"HH:mm"];
NSDate *sourceDate = [formatter dateFromString:dateString];
NSDate is used to represent a date and time. While you can represent just a date by sticking with midnight, you can't really represent just a time of day with it. You can sort of fake this on the Mac (it defaults to some reasonable day), but on iOS you'll get wildly inaccurate times instead. (At least, you do on certain versions. This may have been fixed.)
There's two approaches here:
You can build a NSDateComponents from your time of day and using dateByAddingComponents to add that to midnight on the date you want the time to appear on. This will fail to return the time you expect on a day where daylight savings begins or ends.
You can build a date/time string using the date you want (NSDate) and the time (likely, as a NSString).
- (NSDate *)timeInHours: (NSInteger)hours
minutes: (NSInteger)minutes
seconds: (NSInteger)seconds
onDate: (NSDate *)inDate;
{
id timeStr = [[NSMutableString alloc] initWithFormat: #"%02d:%02d:%02d", hours, minutes, seconds];
id dateStr = [dateWithoutTimeFormatter stringFromDate: inDate];
id dateTimeStr = [[NSString alloc] initWithFormat: #"%# %#", dateStr, timeStr];
[timeStr release];
id dateTime = [dateWithTimeFormatter dateFromString: dateTimeStr];
[dateTimeStr release];
return dateTime;
}
If you really want just the time of day, just keep it around as a string.
Just wanted to post back that I did manage to achieve what I initially set out to do without any issues. Basically, I had to convert the string to NSDate, run that NSDate through a NSDateFormatter (set to the time's original timezone--NSDateFormatter's setTimeZone was helpful), pull an NSDate out of that, and then run that through another NSDateFormatter for the device's timezone. I then converted the resulting NSDate back to NSString, and stuck it on a UILabel.
This solution seems to have worked quite well, as I've set my devices to various timezones, and the timezone change is still correct.
EDIT: this was important to included, too:
NSString *date…….
date = [date stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

How to compare just dates not the time?

How can I compare the dates only, not the time. I am using
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *tempDate = #"2-2-2012"; //Dynamic Date
NSDate *dateString = [dateFormatter dateFromString:tempDate];
NSLog(#"%#",dateString);
It logs this: 2012-02-01 18:30:00 +0000
NSDate *now = [NSDate date];//Current Date
NSLog(#"%#",now);
It logs this: 2011-04-04 14:49:45 +0000
I want to compare Dynamic date and current date, I don't need time. I may not using the correct NSDateFormatter. Can anyone of you tell me how to do this? If I am not clear, please let me know.
Suppose I have to strings
date1 = 3-2-2011;
date2 = 4-5-2020;
I want to convert them in date, only after that I can compare them. Its not happening from my date Formatter. Please have a look.
Thanks!
Simplest way is to compare date by converting it into string.
Sample Code is as shown below:
//Current Date
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
NSString *dateString = [formatter stringFromDate:date];
[formatter release];
//Other Date say date2 is of type NSDate again
NSString *date2String = [formatter stringFromDate:date2];
//Comparison of Two dates by its conversion into string as below
if([date2String isEqualToString:dateString])
{
//Your logic if dates are Equal
}
else if(![date2String isEqualToString:dateString])
{
//Your Logic if dates are Different
}
EDIT:
Checkout this link.
Comparing dates
http://www.iphonedevsdk.com/forum/iphone-sdk-development/64625-how-compare-2-dates.html
Hope This Helps You. :)
Use NSCalendar and NSDateComponents to get a date components object. Then you can look at only those parts of the date that you care about.
If you're just trying to determine whether two dates are the same, regardless of time, one way to go is to use NSDate's -timeIntervalSinceDate: method. If the time interval returned is less than 86,400 seconds (i.e. 24 hours * 60 minutes * 60 seconds) then you can feel fairly sure that it's the same day. Changes related to such things as daylight savings time and leap seconds introduce some possibility of error... if that's a problem, go with NSDateComponents.
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setLocale:[NSLocale autoupdatingCurrentLocale]];
NSString *dateString = [formatter stringFromDate:date];
[formatter release];

NSDateFormatter not returning the correct date

I have the following code which is used to take the time of one NSDate and the current date and combine them into one NSDate. However the formatters are set correctly, but it's returning a date that isn't even close to the one it should be. Here is the code
/* Get the current date and make a formatter to just show the date ONLY */
NSDate *currentDate = [NSDate date];
NSDateFormatter *curDateFormatter = [[NSDateFormatter alloc] init];
[curDateFormatter setDateFormat:#"MM/dd/YYYY"];
/* Create a formatter for the time ONLY */
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:#"hh:mm"];
/* Create a formatter for both date and time */
NSDateFormatter *combinedFormatter = [[NSDateFormatter alloc] init];
[combinedFormatter setDateFormat:#"MM/dd/YYYY hh:mm"];
NSString *combinedDateTime = [NSString stringWithFormat:#"%# %#", [curDateFormatter stringFromDate:currentDate], [timeFormatter stringFromDate:time]];
NSDate *combinedDate = [combinedFormatter dateFromString:combinedDateTime];
/* release the formatters */
[curDateFormatter release];
[timeFormatter release];
[combinedFormatter release];
return combinedDate;
Say it is doing it when this message was posted, it should have 11/10/2010 06:47 but instead it's like 12/27/2009 11:45. Does this in the simulator and the device.
Instead of using the combinedDateFormatter, try the following:
NSDate *combinedDate = [NSDate dateWithNaturalLanguageString:combinedDateTime];
This worked fine for me.
Value for combinedDateTime string was 09/27/2011 11:55
Value for combinedDate date object was 2011-09-27 11:55:00 +0530
Take a look at below URL;
Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

How can I convert a NSString representation of a time value into two NSInteger's containing the hour and minute?

I'm diving into iOS development and the Objective C language and am building an alarm clock app to become familiar with the SDK and language. I have an NSString object that represents a time, with the range "1:00 am" to "12:59 am". I need to convert this NSString into two NSInteger's that contain the hour value and minute value. As I'm doing this, I'm finding the NSString manipulation that I'm doing to be extremely laborious and it just feels like sloppy code.
Is there a simple way to extract the hour and minute characters from a NSString representation of a time value and store their numerical values in two NSInteger's?
Thanks in advance for all your help! I'm gonna get back to it...
NSScanner* timeScanner=[NSScanner scannerWithString:...the time string...];
int hours,minutes;
[timeScanner scanInt:&hours];
[timeScanner scanString:#":" intoString:nil]; //jump over :
[timeScanner scanInt:&minutes];
NSLog(#"hours:%d minutes:%d",hours,minutes);
Use an NSDateFormatter to convert your string into an NSDate.
Use the [NSCalendar currentCalendar] to extract various date components (like the hour, minute, etc).
In other words:
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"h:m a"];
NSDate *date = [formatter dateFromString:#"12:59 pm"];
[formatter release];
NSDateComponents * components = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
NSLog(#"hour: %d", [components hour]);
NSLog(#"minute: %d", [components minute]);
This is the official way, as I know it. It's not pretty:
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc]init] autorelease];
[dateFormatter setDateFormat:#"h:m a"];
NSDate *date = [dateFormatter dateFromString:#"12:34 am"];
[dateFormatter setDateFormat:#"h"];
NSString *hours = [dateFormatter stringFromDate:date];
[dateFormatter setDateFormat:#"m"];
NSString *minutes = [dateFormatter stringFromDate:date];
BUT the string fiddling way of doing it (look for :, look for space, ...), may give you more headaches on the long term.
NSString *time = #"1:00 am";
NSString *removeam = [time stringByReplacingOccurencesOfString:#" am" withString:#""];
SString *removepm = [removeam stringByReplacingOccurencesOfString:#" pm" withString:#""];
NSArray *timeArray = [removepm componentsSeparatedByString:#":"];
NSInteger *hour = [[timeArray objectAtIndex:0] intValue];
NSInteger *mins = [[timeArray objectAtIndex:1] intValue];
If you're building an alarm clock app, you probably will want to look into the NSDate and NSDateFormatter classes, instead of trying to pull all those strings apart into integer types. Also, your time range is a bit weird (maybe a typo?) - don't you want all 24 hours to be available?
get the time interval and write it as
duration.text = [NSString stringWithFormat:#"%d:%02d", (int)audioPlayer.duration / 60, (int)audioPlayer.duration % 60, nil];