gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:20:45 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com