我的dateString
格式为"mm/dd/yyyy '-' HH:mm"
。
我想以字符串中的字符串和小时提取日期。
我尝试过以下代码,但这会返回错误的日期:
- (void) extractDate: (NSString *)dateString intoHour: (NSString *)hourLabel and: (NSString*)dateLabel {
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:@"mm/dd/yyyy '-' HH:mm"];
NSData *date = [formatter dateFromString:dateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:date];
hourLabel = [NSString stringWithFormat:@"%lu:%lu", [components hour], [components minute]];
dateLabel = [NSString stringWithFormat:@"%lu/%lu/%lu", [components day], [components month], [components year]];
}
例如字符串:"05/01/2015 - 11:15"
结果:日期:1/1/2015
,时间:11:15
以及如何维护此日期格式dd/mm/yyyy
,我的意思是当这一天为1
时,它会显示01
答案 0 :(得分:1)
未经测试但是:
本月 MM
。不是mm
,而是分钟。
您已经有NSDateFormatter
,为什么不再使用它而不是NSDateComponents
和NSString
格式?
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"MM/dd/yyyy '-' HH:mm"];
NSDate *date = [formatter dateFromString:dateString];
//Now you have the correct date. So we'll use the NSDateFormatter to transform NSDate (date) into NSString according to the format we need.
[formatter setDateFormat:@"MM/dd/yyyy"];
dateLabel = [formatter stringFromDate:date];
[formatter setDateFormat:@"HH:mm"];
hourLabel = [formatter stringFromDate:date];
hourLabel
/ dateLabel
作为NSString
而非UILabel
是一个误导性的变种命名。