Nguyen Tho
Nguyen Tho

Reputation: 99

Set date format Objective-C

I want to convert this string "Sat, 01 Aug 2015 21:03:59 GMT" to NSDate object

Here's my code

+(NSDate *)getDateFromDateString :(NSString *)dateString {
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"E, dd MMM yyyy HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:dateString];
return date;}

but date always is nil. I guess something wrong with date format. Can someone please give me some advice?

Upvotes: 0

Views: 195

Answers (2)

Nguyen Tho
Nguyen Tho

Reputation: 99

Thanks for your support, i found out the answer. Need to declare the locale

[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

Upvotes: 1

l'L'l
l'L'l

Reputation: 47169

Normally this is how I would call a utility function:

DateHelperClass.h

+ (NSDate *)getDateFromDateString :(NSString *)dateString;

DateHelperClass.m

+ (NSDate *)getDateFromDateString :(NSString *)dateString
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
    NSDate *date = [dateFormatter dateFromString:dateString];
    return date;
}

SomeOtherClass.m

#import "DateHelperClass.h"

- (void)convertDate
{
    NSLog(@"%@",[DateHelperClass getDateFromDateString:@"Sat, 01 Aug 2015 21:03:59 GMT"]);
} 

Result:

2015-08-01 21:03:59 +0000

Upvotes: 0

Related Questions