Objective-C and iOS SDK provide a class to help formatting date (marshaling and unmarshaling), this class is NSDateFormatter. No surprise, the NSDateFormatter uses the Unicode Date Format Patterns.
A small example of date creating from a string:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate *date = [dateFormatter dateFromString:publicationDate ]; [dateFormatter release]; // use your date object
The date that I have to create from a sting looks like "2010-11-12". So I do not have any time information. When I do convert this string with the code above, the result is "2010-11-11 23:00:00 +0000". As you can see the date is calculated from my current time zone, small reminder I am in France. So the "date" object itself is perfectly fine, but in my example I want to have the date independently of the time.
To be able to manage the date without any time/timezone information, I can force the timezone I want to use when using the NSDateFormatter class. I just need to use the setTimeZone instance method.
The code looks like that now (see line#3):
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; NSDate *date = [dateFormatter dateFromString:publicationDate ]; [dateFormatter release]; // use your date object
Hope that helps!
Thanks for the tip!
ReplyDeleteIf you want to store these time in a database or send it over the server...best is to use Unix timestamps. Here's a little snippet to get that:
ReplyDelete+ (NSTimeInterval)getUTCFormateDate{
NSDateComponents *comps = [[NSCalendar currentCalendar]
components:NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit
fromDate:[NSDate date]];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:[[NSTimeZone systemTimeZone] secondsFromGMT]];
return [[[NSCalendar currentCalendar] dateFromComponents:comps] timeIntervalSince1970];
}
Thanks for the tips this was driving me crazy !
ReplyDeleteThanks for this quick tip, it does exactly what I needed.
ReplyDeleteThanks for this little tip, it did exactly what I needed!
ReplyDelete