简体   繁体   English

从NSString获取NSDate

[英]get NSDate from NSString

I have current date and time in PST format as a string such as 我有PST格式的当前日期和时间,例如字符串

currentDateStr 06/02/11 05:40:33 PDT

Could anyone tell me how to convert this string into NSDate. 谁能告诉我如何将此字符串转换为NSDate。

Thanx in advance. 提前感谢。

From this SO question NSDate expressed in different time zones, ie local time zone (GMT-400) to PST 从这个SO问题中, NSDate在不同时区表示,即本地时区(GMT-400)到PST

 NSDate always returns relative to GMT 

This doesn't make sense. 这没有道理。 NSDate just encapsulates an absolute moment in time (let's forget about relativity for a second) and it has no concept of time zones whatsoever. NSDate只是封装了一个绝对的时间(让我们暂时忘记了相对性),并且它没有任何时区的概念。 To say that NSDate times are relative to GMT is wrong. 说NSDate时间相对于GMT是错误的。

To output a date in a specific time zone, you should create an instance of NSDateFormatter and call setTimeZone: on it to set the time zone. 要在特定时区输出日期,您应该创建一个NSDateFormatter实例并在其上调用setTimeZone:来设置时区。 According to the Unicode docs, the format string @"zzz" should output the time zone value as "PST". 根据Unicode文档,格式字符串@“ zzz”应该将时区值输出为“ PST”。

NSTimeZone *tz = [NSTimeZone timeZoneWithName:@"PST"]; // for PST

I guess your date formatter settings are wrong. 我猜您的日期格式设置错误。 Try with the following: 请尝试以下操作:

[formatter setDateFormat: @"MM/dd/yy HH:mm:ss a"];

Best of luck 祝你好运

If you are using a ISO8601 complint string for the date I recommend using the parser as made by Peter Hosey http://boredzo.org/iso8601dateformatter/ 如果您使用ISO8601混合字符串作为日期,则建议使用彼得·霍西(Peter Hosey)制作的解析器http://boredzo.org/iso8601dateformatter/

NSDate *isoDateFromString = [yourISO8601dateformatterObject dateFromString:iso8601DateString];

This will give you a NSDate without you fussing with timezone and stuff. 这将为您提供NSDate,而您无需大意时区和其他内容。

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

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