user836026
user836026

Reputation: 11350

how to convert NSString to NSDate

i tried to convert this NSString date to NSDate

NSString *update_time= @"2012-03-09 14:54:30.0";

// convert to date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss'.0'"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Melbourne"]];
NSDate *dte = [dateFormat dateFromString:update_time ];
NSLog(@"Date: %@", dte);

but i'm getting Date: (null)

Upvotes: 0

Views: 231

Answers (3)

Vu Tran
Vu Tran

Reputation: 610

You're missing a pointer.

  NSString * update_time= @"2012-03-09 14:54:30.0";

// convert to date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss'.0'"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+4"]];
NSDate *dte = [dateFormat dateFromString:update_time ];
NSLog(@"Date: %@", dte);

Upvotes: 1

AppyMike
AppyMike

Reputation: 2064

NSString *update_time= @"2012-03-09 14:54:30.0";

Missing the pointer

Upvotes: 2

omz
omz

Reputation: 53551

"GMT+4" is not a valid timzone name. Use timeZoneForSecondsFromGMT: instead:

//...
NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:4 * (60 * 60)];
[dateFormat setTimeZone:timeZone];
//...

If you want to use timeZoneWithName:, you can get a list of valid timezone names using [NSTimeZone knownTimeZoneNames]. Those all have the form "Europe/Berlin" etc.

Upvotes: 2

Related Questions