使用NSDateFormatter设置UIDatePicker日期 [英] Setting UIDatePicker date with NSDateFormatter

查看:84
本文介绍了使用NSDateFormatter设置UIDatePicker日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试初始化一个UIDatePicker,其日期是在我的会话早期从该日期选择器返回给我的。这是库存计划的一部分,需要获取库存项目上次校准的日期。

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.

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

Using this code I receive a date/time string:

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

我最终在calDate中使用以下字符串:2011-11-11 21:56:38 + 0000

I end up with the following string in 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];
    }
}

NSLog验证字符串是否仍然有效。
如果我在if(date!= nil)上设置断点,它会显示date = nil。

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.

提前致谢。

推荐答案

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

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

此代码:

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

输出:

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

没有Z:

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

输出:

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

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

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

这篇关于使用NSDateFormatter设置UIDatePicker日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆