我试图显示当前的日期和时间。目前的日期和时间运作良好,这是我的代码:
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd MMM YYYY hh:mm a"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
_dateLabel.text=dateString;
我需要的是。我需要显示我的时间:
例如现在这个问题的发布时间是1:42pm
。我想这样:
1 - 2 pm
但是对于我得到的上述代码:1:42 pm
。我需要这样:
1 - 2 pm
请帮我解决1小时的问题。
谢谢!
答案 0 :(得分:2)
- (NSString *)dateString {
NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd MMM yyyy"];
NSString *dateString = [dateFormatter stringFromDate:currentDate];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitHour fromDate:currentDate];
NSInteger hour = [components hour];
NSInteger nextHour = [components hour] + 1;
NSString *nextHourDateString = @"";
if (nextHour == 24) {
nextHour = 0;
NSTimeInterval oneHour = 60 * 60;
NSDate *nextHourDate = [NSDate dateWithTimeInterval:oneHour sinceDate:currentDate];
nextHourDateString = [[dateFormatter stringFromDate:nextHourDate] stringByAppendingString:@" "];
}
NSString *hourSuffix = hour > 12 ? @" pm" : @" am";
NSString *nextHourSuffix = nextHour > 12 ? @" pm" : @" am";
if ([hourSuffix isEqualToString:nextHourSuffix]) {
hourSuffix = @"";
}
return [NSString stringWithFormat:@"%@ %ti%@ - %@%ti%@",
dateString,
[self hourInTwelveHourFormat:hour],
hourSuffix,
nextHourDateString,
[self hourInTwelveHourFormat:nextHour],
nextHourSuffix];;
}
- (NSInteger)hourInTwelveHourFormat:(NSInteger)hour {
if (hour > 12) {
hour -= 12;
}
return hour;
}