在iOS中将NSdate四舍五入为最近的小时

eivnm1vs  于 2023-03-20  发布在  iOS
关注(0)|答案(6)|浏览(242)

我有数据格式
时间:十三时五十二分,十时三十分,十一时四十八分
等等
我想四舍五入到最接近的小时。
比如13:52 -〉14:00,10:30 -〉11:00和11:48 -〉12:00。
如何使用NSDate实现这一点?

3npbholx

3npbholx1#

下面是Swift 3.0的一个实现,它使用Date扩展来获取最接近的小时数:

extension Date {
    func nearestHour() -> Date? {
        var components = NSCalendar.current.dateComponents([.minute], from: self)
        let minute = components.minute ?? 0
        components.minute = minute >= 30 ? 60 - minute : -minute
        return Calendar.current.date(byAdding: components, to: self)
    }
}
wbgh16ku

wbgh16ku2#

使用此方法

- (NSDate*) nextHourDate:(NSDate*)inDate{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components: NSEraCalendarUnit|NSYearCalendarUnit| NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit fromDate: inDate];
    [comps setHour: [comps hour]+1]; //NSDateComponents handles rolling over between days, months, years, etc
    return [calendar dateFromComponents:comps];
}

这将为您提供inDate的下一小时日期

ep6jt1vc

ep6jt1vc3#

func nextHourDate() -> NSDate? {
    let calendar = NSCalendar.currentCalendar()
    let date = NSDate()
    var minuteComponent = calendar.components(NSCalendarUnit.MinuteCalendarUnit, fromDate: date)
    let components = NSDateComponents()
    components.minute = 60 - minuteComponent.minute
    return calendar.dateByAddingComponents(components, toDate: date, options: nil)
}
oiopk7p5

oiopk7p54#

由于以下几个原因,使用组件并不可靠:
1.不考虑秒数
1.添加秒时,很少会遗漏一秒
我在**Swift 4.***中找到的最可靠的方法是:

extension Date {
    func nearestHour() -> Date {
        return Date(timeIntervalSinceReferenceDate:
                (timeIntervalSinceReferenceDate / 3600.0).rounded(.toNearestOrEven) * 3600.0)
    }
}
ycl3bljg

ycl3bljg5#

使用下面的代码。它一定对你有帮助。

NSString *dateString=@"17:15";
    NSArray *strings = [dateString componentsSeparatedByString:@":"];

int firstPart=[[NSString stringWithFormat:@"%@",strings[0]] intValue];
int lastPart=[[NSString stringWithFormat:@"%@",strings[1]] intValue];

NSLog(@"LAST:%d",firstPart);

if (lastPart>0) {

    int output=firstPart+1;


    NSString *finalOutput=[NSString stringWithFormat:@"%d:00",output];

     NSLog(@"OUTPUT:%@",finalOutput);
}
else
{
     NSLog(@"OUTPUT:%@",dateString);
}
w6lpcovy

w6lpcovy6#

这是Swift 4/5版本-

func nextHourDate() -> Date? {
    let calendar = Calendar.current
    let date = Date()
    var minuteComponent = calendar.component(.minute, from: date)
    var components = DateComponents()
    components.minute = 60 - minuteComponent
    return calendar.date(byAdding: components, to: date)
}

相关问题