【问题标题】:Extract Date and Hour from NSDate - Objective C从 NSDate 中提取日期和时间 - Objective C
【发布时间】:2016-03-31 16:09:06
【问题描述】:

我有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

【问题讨论】:

  • MM 为该月,否则为分钟(因为您已经使用过)。如果需要,NSNumberFormatter 可以使用前导零。或者你可以从你得到的日期使用NSDateFormatter,而不是使用NSDateComponents[formatter setDateFormat:@"MM/dd/yyyy"]; dateLabel = [formatter stringFromDate:date]; [formatter setDateFormat:@"HH:mm"]; hourLabel = [formatter stringFromDate:date];顺便说一下hourLabel/dateLabel作为NSString而不是UILabel是一个相当误导的变量命名.
  • 您应该使用NSDateFormatter 来执行此操作。但是为了您的兴趣,使用[NSString stringWithFormat:@"%02d", [components day]] 会为您完成这项工作,
  • 如何使用NSDateFormatter获取字符串中的各个部分

标签: ios objective-c nsdate nsdateformatter nsdatecomponents


【解决方案1】:

未测试但:

MM 这个月。不是mm,而是分钟。

您已经有一个NSDateFormatter,为什么不再次使用它而不是NSDateComponentsNSString 格式?

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 as NSString 而不是 UILabel 是一种误导性的 var 命名。

【讨论】:

    猜你喜欢
    • 2011-12-13
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多