Brittany
Brittany

Reputation: 1439

Obj-c - Convert String to NSDate?

I'm trying to convert text that appears in my cell's UILabel to an NSDate format. For some reason, my below code doesn't work, even though my string (timeEnd) contains a value? The output of timeEnd is: 19-08-2018 17:38 , and yet for some reason my conversion result is (NULL)?

ViewController.m

NSString *timeEnd = filteredSwap[indexPath.row][@"endswaptime"];
cell.endTime.text = timeEnd;

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM y hh:mm a zzz"];
NSLog(@"Date is: %@", [dateFormatter dateFromString:timeEnd]);

Upvotes: 1

Views: 94

Answers (3)

Midhun
Midhun

Reputation: 2177

        NSString *timeString = @"01/03/2018";

        NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
        NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
        [dateFormatter setTimeZone:timeZone];

        result = [dateFormatter dateFromString:timeString];

Upvotes: 0

Daljeet
Daljeet

Reputation: 1595

Use the below code to get your date:

     NSString *timeEnd = filteredSwap[indexPath.row][@"endswaptime"];        
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-mm-yyyy HH:mm"];
    NSLog(@"Date is: %@", [dateFormatter dateFromString:timeEnd]);

Upvotes: 2

Caleb
Caleb

Reputation: 124997

The output of timeEnd is: 19-08-2018 17:38 , and yet for some reason my conversion result is (NULL)?

The format of your string doesn't match the format you use for the date formatter. NSDateFormatter therefore can't create a valid date using the format you gave it, and it returns nil.

Upvotes: 1

Related Questions