ios - 如何获得时间(下午 1 - 2 点)或(下午 2 - 3 点)

标签 ios objective-c nsdate nsdateformatter

我已尝试显示当前日期和时间。当前日期和时间运行良好,这是我的代码:

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 点

但对于上面的代码,我得到:1:42 pm。我需要这样:

1 - 2 pm

请帮助我如何完成 1 小时的时段。

谢谢!

最佳答案

- (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;
}

关于ios - 如何获得时间(下午 1 - 2 点)或(下午 2 - 3 点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35427123/

相关文章:

ios - 如何在 Material-UI 中以与 iOS UITableView 中相同的方式设置 ListSubheader 的样式?

objective-c - 游戏中心特定配对

cocoa - 在 NSUserDefaults 中存储 NSDate 的最佳方式是什么?

ios - NSDate formatString 有时返回 nil

iphone - NSDate 保留发送到释放实例的消息

ios - 这是 NSOperation 的有效 'main' 方法吗?

iOS Objective C - 使用长按创建 View /在相同的 UIView 上使用多个手势

ios - 是否可以从我的应用程序启动 Apple Pay NFC?

objective-c - 在 Xcode 中使用 Yacc 和 Lex

ios - drawViewHierarchyInRect :afterScreenUpdates: delays other animations