简体   繁体   English

将 NSString 转换为 NSDate 不起作用

[英]Convert NSString to NSDate is not working

i use code same this best answer我使用相同的代码这个最佳答案

Converting NSString to NSDate (and back again) 将 NSString 转换为 NSDate(并再次返回)

NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];

but dateFromString result is 2010-01-31 17:00:00 +0000 why it not same day.但是 dateFromString 结果是 2010-01-31 17:00:00 +0000 为什么不是同一天。
i cannot compare date.我无法比较日期。

这是因为你当前的时区,添加这个然后它会给你正确的日期

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

Add the following line right after where you have set the date format.在您设置日期格式的位置之后添加以下行。 It because it will convert by default with local timezone of the device.这是因为它会默认转换为设备的本地时区。 It works for me!这个对我有用!

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

It is actually the same date.实际上是同一天。 But the date formatter, by default, parses the date string in the local timezone of the device if a timezone is not passed in. In your case, your date was intepreted as Midnight February 2nd 2010 UTC+7 which is January 31st 2010 17:00 UTC.但是,默认情况下,如果未传入时区,则日期格式化程序会解析设备本地时区中的日期字符串。在您的情况下,您的日期被解释为 2010 年 1 月 31 日 UTC+7 午夜 2010 年 1 月 31 日: 00 世界标准时间。

If the date string is always in UTC, pass in the UTC timezone into the date formatter like this:如果日期字符串始终采用 UTC,请将 UTC 时区传入日期格式化程序,如下所示:

NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];

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

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