简体   繁体   English

如何使用NSDateFormatter将NSString转换为NSDate?

[英]How to convert NSString to NSDate using NSDateFormatter?

I getting the date from the webservice like "2012-07-03 07:26:48". 我从网络服务获取日期,如“2012-07-03 07:26:48”。 I have saved in NSString after parsing from webservice. 我从webservice解析后保存在NSString中。 While convert the NSString to NSDate used below code, 在将NSString转换为NSDate时使用下面的代码,

    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
    [dateFormatter1 setDateFormat:@"yyyy-MM-dd hh:mm:ss"];

    NSString *dateStr = @"2012-07-03 07:26:48";
    NSDate *date = [dateFormatter1 dateFromString:dateStr];
    NSLog(@"Date : %@", date);
   The NSLog value is "2012-07-03 01:56:48 +0000";

The NSLog value is "2012-07-03 01:56:48 +0000"; NSLog值为“2012-07-03 01:56:48 +0000”; I don't know why the time has changed. 我不知道为什么时间变了。 Can anyone please help me to do this? 有人可以帮我这样做吗?

You need to put timezone as: 您需要将时区设为:

theDateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

Because it is considering GMT time format. 因为它正在考虑GMT时间格式。

您必须设置NSDateFormatter的时区。

默认情况下,日期以utc格式保存,同时将字符串转换为nsdate ...您可以将日期中的原始时间作为字符串...如果要更改时区,请使用dateformatter进行更改..否则不要更改

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

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