iosobjective-cnsdateformatter

Objective-C dateformatter. yyyy-MM-dd hh:mm:ss change to yyyy-MM-dd


How to getting Dateformat yyyy-MM-dd from string yyyy-MM-dddd hh:mm:ss

NSString *dateValue = self.selectedReward.expires_at;
NSLog(@"Date value --- %@", dateValue);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [formatter dateFromString:dateValue];
[cell.lblExpire setText:[NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"lbl_Expired_On", nil),dateValue]];
NSLog(@"date %@", date);

2018-10-24 14:58:02.141296+0800 TKBakery[21601:277978] Date value ---2018-10-15 15:37:00

2018-10-24 14:58:02.141878+0800 TKBakery[21601:277978] date---- (null)


Solution

  • In your question, you have clearly mentioned the date format also then why are used the wrong format

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //2018-10-15 15:37:00   
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [formatter dateFromString:dateValue];
    NSLog(@"date %@", date);
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *getFinalDate = [formatter stringFromDate:dateValue];
    NSLog(@"final Date %@", getFinalDate);
    

    for more info see this sample output