Mani
Mani

Reputation: 1841

How to convert an NSString to an NSDate with time?

I am trying to convert an NSString to an NSDate with time. Here's what I'm doing now:

 NSString *myDateIs= @"2012-07-14 11:30:40 AM ";
 NSDateFormatter* startTimeFormat = [[NSDateFormatter alloc] init];
 [startTimeFormat setDateFormat:@"YYYY-MM-dd hh:mm:ss a "];
 NSDate*newStartTime = [startTimeFormat dateFromString:myDateIs];

The output is 2012-07-14 06:00:40 +0000. The date is correct but the time is not correct. How can I get the correct time? Thanks.

Upvotes: 0

Views: 742

Answers (4)

Pfitz
Pfitz

Reputation: 7344

This one will work for you:

[startTimeFormat setDateFormat:@"YYYY-MM-dd hh:mm:ss aa"];
[startTimeFormat setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

You missed an a at the dateFormat and have to set the timeZone.

Upvotes: 1

Alexey
Alexey

Reputation: 7247

You need to set the timezone.

NSString *myDateIs= @"2012-07-14 11:30:40 AM ";
NSDateFormatter* startTimeFormat = [[NSDateFormatter alloc] init];
startTimeFormat.timeZone=[NSTimeZone timeZoneWithName:@"UTC"];
[startTimeFormat setDateFormat:@"YYYY-MM-dd hh:mm:ss a"];
NSDate*newStartTime = [startTimeFormat dateFromString:myDateIs];
NSLog(@"%@", newStartTime);

Output:

 2012-07-14 11:30:40 +0000

Upvotes: 1

msk
msk

Reputation: 8905

The time you are getting is in GMT convert it into local time.

NSDateFormatter* local = [[[NSDateFormatter alloc] init] autorelease];        
[local setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
[local setDateFormat:@"YYYY-MM-dd hh:mm:ss a"];

NSString* localSTR = [local stringFromDate: newStartTime];

Upvotes: 2

Cameron Lowell Palmer
Cameron Lowell Palmer

Reputation: 22245

Time Zone. The NSDate will store the time in terms of GMT. However your local time zone is probably quite different.

Upvotes: 1

Related Questions