xcode 使用 NSDateFormatter 设置 UIDatePicker 日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8720708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 22:53:49  来源:igfitidea点击:

Setting UIDatePicker date with NSDateFormatter

iosxcodeipad

提问by schaz

I am trying to initialize a UIDatePicker with a date that was returned to me from that date picker earlier in my session. This is part of an inventory program that needs to get the date that in inventory item was last calibrated.

我正在尝试使用一个日期来初始化 UIDatePicker,该日期是在我的会话早些时候从该日期选择器返回给我的。这是库存程序的一部分,需要获取库存项目上次校准的日期。

Using this code I receive a date/time string:

使用此代码我收到一个日期/时间字符串:

NSDate *choice = [pickedDate date];
calDate = [[NSString alloc] initWithFormat:@"%@", choice];

I end up with the following string in calDate: 2011-11-11 21:56:38 +0000

我在 calDate 中得到以下字符串:2011-11-11 21:56:38 +0000

I am trying to set my date picker with the following code:

我正在尝试使用以下代码设置我的日期选择器:

NSDate *date = [[[NSDate alloc] init] retain];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"cal date = %.@.",drawingInfo.drawingDate);
if([calDate length] != 0) {
    date = [dateFormatter dateFromString:calDate];

    if(date != nil) {
            [pickedDate setDate:date animated:NO];
    }
}

The NSLog verifies that the string is still in tact. If I put a breakpoint on the if(date != nil) it shows me that date = nil.

NSLog 验证字符串是否仍然完整。如果我在 if(date != nil) 上放置一个断点,它会显示 date = nil。

Thanks in advance.

提前致谢。

回答by bryanmac

You're missing the Z format specifier in the date format.

您在日期格式中缺少 Z 格式说明符。

This code:

这段代码:

NSString *calDate = @"2011-11-11 21:56:38 +0000";
NSDate *date = [[[NSDate alloc] init] retain];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];  
//                                   right here    ^

date = [dateFormatter dateFromString:calDate];

NSLog(@"date:%@", date);

Outputs:

输出:

2012-01-03 20:14:15.258 Craplet[38753:707] date:2011-11-11 21:56:38 +0000

Without the Z:

没有 Z:

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

It outputs:

它输出:

2012-01-03 20:16:10.456 Craplet[38885:707] date:(null)

If the format cannot be matched to the date string, it returns nil

如果格式不能与日期字符串匹配,则返回 nil