【问题标题】:DatePicker returns unexpected date in iOSDatePicker 在 iOS 中返回意外的日期
【发布时间】:2014-04-14 07:12:42
【问题描述】:

我从日期选择器中获得了意想不到的价值。它附加到文本字段。在文本字段中,我得到的当前日期很好,但是在分配给属性时它给出了意外的值。我在这里错过了什么?

property (strong, nonatomic) LAClaimReport *claimReport;
LAClaimReport is an entity in my coreDB.

      NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
        [dateFormat setDateFormat:@"dd/MM/YYYY"];
        NSLog(@"Date incident1 %@" , self.dateOfIncidentTextField.text); // it returns correct value , today's date (14/04/2014).
        _claimReport.dateOfIncident = [dateFormat dateFromString:self.dateOfIncidentTextField.text];
        NSLog(@"Date incident2 %@" , _claimReport.dateOfIncident); // here gives unexpected value.(2013-12-21 18:30:00 +0000)

日志: 事件日期1 2014 年 4 月 14 日 事件日期2 2013-12-21 18:30:00 +0000

请指导。谢谢

【问题讨论】:

    标签: ios iphone objective-c date datepicker


    【解决方案1】:

    日期格式字符串区分大小写。应该是dd/MM/yyyy。小 'y' 不是大写 'Y'。如果您正确设置时区,它将输出正确的日期。

    这两者的区别在link中提到了:

    Y 1..n 1997 Year (in "Week of Year" based calendars). Normally the length specifies the padding, but for two letters it also specifies the maximum length. This year designation is used in ISO year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems where week date processing is desired. May not always be the same value as calendar year.
    
    y 1..n 1996 Year. Normally the length specifies the padding, but for two letters it also specifies the maximum length.
    

    更多关于年度日历here

    【讨论】:

    • 谢谢@ShantiK。只是想知道 YYYY 是如何产生影响的。你能简单地说一下吗?备查?谢谢。
    【解决方案2】:

    在你的 .m 文件中创建一个变量

    UIDatePicker *datePicker ;
    

    在 textFieldDidBeginEditing 中

    -(void)textFieldDidBeginEditing:(UITextField *)textField
    {
    
      datePicker = [[UIDatePicker alloc] init];
      datePicker.datePickerMode = UIDatePickerModeDate;
      datePicker.minimumDate  = [NSDate date];
      [datePicker addTarget:self action:@selector(method:) forControlEvents:UIControlEventValueChanged];
      textField.inputView = datePicker;
    }
    
    
    
    -(void)method:(id)sender
    {
      UIDatePicker *datePickerVlaue = (UIDatePicker *)sender;
      NSDateFormatter *df = [[NSDateFormatter alloc] init];
      [df setDateFormat:@"dd/MM/yyyy"];
      NSString *formattedDate = [df stringFromDate:[datePickerVlaue date]];
      self.yourTextField.text = [NSString stringWithFormat:@"%@",formattedDate];
    }
    

    【讨论】:

      【解决方案3】:

      将格式@"dd/MM/YYYY"更改为@"dd/MM/yyyy"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-27
        • 2018-09-16
        • 1970-01-01
        • 2018-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多