如何从字符串yyyy-MM-dddd hh:mm:ss获取Dateformat yyyy-MM-dd
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]日期值--- 2018-10-15 15:37:00
2018-10-24 14:58:02.141878 + 0800 TKBakery [21601:277978]日期----(空)
答案 0 :(得分:1)
将字符串转换为具有正确格式的日期,然后将该日期更改为具有所需格式的字符串。
按如下所示更改代码:
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);
答案 1 :(得分:1)
在您的问题中,您还明确提到了日期格式,然后为什么使用了错误的格式
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);
有关更多信息,请参见此示例output