简体   繁体   English

如何随着时间将NSString转换为NSDate?

[英]How to convert an NSString to an NSDate with time?

I am trying to convert an NSString to an NSDate with time. 我试图随着时间将NSString转换为NSDate 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 . 输出为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. 谢谢。

The time you are getting is in GMT convert it into local time. 您所获得的时间是格林尼治标准时间(GMT),将其转换为当地时间。

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

Time Zone. 时区。 The NSDate will store the time in terms of GMT. NSDate将按照格林尼治标准时间存储时间。 However your local time zone is probably quite different. 但是,您当地的时区可能完全不同。

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

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. 您错过了dateFormat的a,必须设置timeZone。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM