简体   繁体   English

从UIDatePicker中选择正确的日期格式

[英]To pick the correct date format from UIDatePicker

I have created an app to fetch the date of birth of a person. 我创建了一个应用程序来获取一个人的出生日期。 I have used UITextBox to take the user's date of birth from UIDatePicker(shows when user click on UITextBox). 我已经使用UITextBox从UIDatePicker获取用户的出生日期(当用户单击UITextBox时显示)。 When I select the date, month and year, and click on set then the date shows in the UITextBox but days are not in correct format. 当我选择日期,月份和年份,然后单击设置时,日期将显示在UITextBox中,但日期格式不正确。 When I set the date 02/16/1993(MM/DD/YYYY) then I got 02/47/1993 in UITextBox.Days are added (31 + 16 = 47), But i want to show 02/16/1993. 当我设置日期02/16/1993(MM / DD / YYYY)时,我在UITextBox中得到了02/47 / 1993.Days被添加了(31 + 16 = 47),但是我想显示02/16/1993。 My code is: 我的代码是:

NSArray *allViews=[dateSheet subviews];
    for (UIView *subView in allViews)
    {
        if ([subView isKindOfClass:[UIDatePicker class]])
        {
            self.birthdate=[(UIDatePicker *)subView date];
        }
    }
    NSDateFormatter *dateFormatter= [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    [txtDOB setText:[dateFormatter stringFromDate:self.birthdate]];

What should I do to get correct format? 我应该怎么做才能获得正确的格式?

Clearly the problem is with the day being displayed as 'day of the year' rather than 'day of the month'. 显然,问题在于将日期显示为“一年中的某天”,而不是“月份中的某天”。 Which may likely be because of you using 'DD' instead of 'd' for calculating day.. 这可能是由于您使用“ DD”而不是“ d”来计算日期。

See: http://www.unicode.org/reports/tr35/tr35-19.html#Date_Format_Patterns 参见: http : //www.unicode.org/reports/tr35/tr35-19.html#Date_Format_Patterns

You can fix that in 'setDateFormat' string. 您可以在“ setDateFormat”字符串中进行修复。 Otherwise I will suggest you to use NSDateComponents, that will not only give accurate results but also a low margin of error... 否则,我建议您使用NSDateComponents,它不仅可以提供准确的结果,而且误差率也较低。

Can you try this: 你可以尝试一下:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    NSString *strDate = [dateFormat stringFromDate:datePicker.date];
    txtDOB.text = strDate;

But I think there's something wrong in setting up your date picker. 但是我认为设置日期选择器有问题。 You should declare the date picker in your .h file. 您应该在.h文件中声明日期选择器。

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

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