-1

I am trying to get the time of day from a date string. The following string should return 12:00AM.

2010-08-24 00:00:00 +0000

But using the following code, my NSDate object returns nil when it reaches the log statement. What is the issue here? Thanks!

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"h:mma"];
NSDate *date = [df dateFromString:@"2010-08-24 00:00:00 +0000"];
NSLog(@"DATE: %@", [date description]);

Output: DATE: (null)

Pheepster
  • 6,045
  • 6
  • 41
  • 75

2 Answers2

1

Try this one:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"YYYY-MM-dd hh:mm:ss ZZZZ"];
NSDate *date = [df dateFromString:@"2010-08-24 00:00:00 +0000"];
NSLog(@"DATE: %@", [date description]);

Cheers!

Tested on playgorund:

enter image description here

D33pN16h7
  • 2,030
  • 16
  • 20
0

Well you can use the following procedure to extract time from the date string

1.Get NSDate object in its given format.

2.Set the NSDateFormatter object with the required format.

3.Get the date string in required format.

 - (BOOL)application:(UIApplication *)
application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    NSString *date = [self convertDate:@"2010-08-24 00:00:00 +0000"
                            fromFormat:@"yyyy-MM-dd HH:mm:ss ZZZZ"
                              toFormat:@"hh:mm a"];

    NSLog(@"DATE: %@", [date description]);

    return YES;
}


- (NSString *)convertDate:(NSString *)inDateString
             fromFormat:(NSString *)fromFormat
               toFormat:(NSString *)toFormat
{
    NSDateFormatter *dateFormatter = nil;
    NSString *outDateString = nil;
    NSDate *date = nil;

    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:fromFormat];

    date = [dateFormatter dateFromString:inDateString];

    [dateFormatter setDateFormat:toFormat];
    outDateString = [dateFormatter stringFromDate:date];

    return outDateString;
}
ImAshwyn
  • 26
  • 4