简体   繁体   中英

DatePicker returns unexpected date in iOS

I am getting unexpected value from date picker. It's attached to text field. In text fields, i am getting current date that is fine but when assigning to property it gives unexpected value. What am i missing here?

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)

Log : Date incident1 14/04/2014 Date incident2 2013-12-21 18:30:00 +0000

pls guide. Thanks

The date format string is case sensitive. It should be dd/MM/yyyy . Small ' y ' not capital ' Y '. Then it will output the correct date if you set the time zone correctly.

The difference between the two is mentioned in this 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.

More about Week of Year calendars here

create a variable in your .m file

UIDatePicker *datePicker ;

in 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];
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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