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
  • 34,719
  • 24
  • 185
  • 251
joey
  • 73
  • 2
  • 13

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
  • 3,543
  • 1
  • 29
  • 42
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,511
  • 3
  • 20
  • 26
Anbu.Karthik
  • 80,161
  • 21
  • 166
  • 138