1
votes

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?

3
Keep in mind, [[NSDateFormatter alloc] init] is an expensive operation. Better to cache the result. - Berik
Thanks, but in this case I don't care much about this, because it is not working((( - Anatoliy Gatt

3 Answers

2
votes

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];
1
votes

Please find the correct NSDateFormatter formatting string here.

0
votes

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];