0

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)

Cœur
  • 37,241
  • 25
  • 195
  • 267
joey
  • 73
  • 2
  • 14

2 Answers2

1

Convert the string to date with proper format then change that date to string with the format you need.

Change the code as follows:

NSString *dateValue = self.selectedReward.expires_at;
NSLog(@"Date value --- %@", dateValue);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //change the format
NSDate *date = [formatter dateFromString:dateValue];
//add this:
[formatter setDateFormat:@"yyyy-MM-ss"];
NSString *dateStr = [formatter stringFromDate:date];
[cell.lblExpire setText:[NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"lbl_Expired_On", nil),dateStr]];
NSLog(@"date %@", dateStr);
Arnab
  • 4,216
  • 2
  • 28
  • 50
1

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

Ravi Dhorajiya
  • 1,531
  • 3
  • 21
  • 26
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143