Anatoliy Gatt
Anatoliy Gatt

Reputation: 2491

NSDateFormatter and NSString to NSDate conversion

Good day, I'm trying to convert NSString that I'm getting from the server to NSDate object. That is the code:

NSString *date = @"Sep 12 at 12:03 am";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMM d 'at' H:m a"];
self.messageDateAndTime = [dateFormatter dateFromString:date];
NSLog(@"NSDate: %@", self.messageDateAndTime);

I'm getting date in the format that date string has. After I'm trying to create my own formatter for this date format. But anyway, I'm getting null!

What I'm doing wrong?

Upvotes: 1

Views: 1950

Answers (3)

Berik
Berik

Reputation: 8143

Please find the correct NSDateFormatter formatting string here.

Upvotes: 1

Anatoliy Gatt
Anatoliy Gatt

Reputation: 2491

I found the solution my self, it would return null until you set the locale yourself. This is the code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
[dateFormatter setDateFormat:@"MMM d 'at' H:m a"];
self.messageDateAndTime =[dateFormatter dateFromString:messageDate];

Upvotes: 0

prashant
prashant

Reputation: 1920

I debug you above code its running fine and giving NSDate: 1970-09-11 18:33:00 +0000 this log. Check for you string first. For more you can use the category below.

// NSString+Date.h
@interface NSString (Date)
+ (NSDate*)stringDateFromString:(NSString*)string;
+ (NSString*)stringDateFromDate:(NSDate*)date;
@end


// NSString+Date.m
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];

NSDate *date = [dateFormatter dateFromString:stringDate ];
[dateFormatter release];
+ (NSDateFormatter*)stringDateFormatter
{
    static NSDateFormatter* formatter = nil;
    if (formatter == nil)
    {
        formatter = [NSDateFormatter alloc] init];
        [formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
    }   
    return formatter;
}

+ (NSDate*)stringDateFromString:(NSString*)string
{
    return [[NSString stringDateFormatter] dateFromString:string];
}

+ (NSString*)stringDateFromDate:(NSDate*)date
{
    return [[NSString stringDateFormatter] stringFromDate:date];
}


// Usage (#import "NSString+Date.h")
NSString* string = [NSString stringDateFromDate:[NSDate date]];
NSDate* date = [NSString stringDateFromString:string];

Upvotes: 2

Related Questions