Reputation: 2587
I have data in the format
time: 13:52, 10:30, 11:48
etc
I would like to round to the nearest hour.
like for 13:52 -> 14:00 , 10:30 -> 11:00 and 11:48 -> 12:00.
How can I do that with NSDate?
Upvotes: 8
Views: 9682
Reputation: 1
func nextHour() -> Date? {
guard let date = Calendar.current.date(byAdding: .hour, value: 1, to: self) else { return nil }
return Calendar.current.dateComponents([.era, .year, .month, .day, .hour], from: date).date
}
Upvotes: -1
Reputation: 2483
Here is Swift 4/5 version -
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)
}
Upvotes: 0
Reputation: 6526
Using components is not reliable due to a couple of reasons:
The most reliable way I found in Swift 4.* is:
extension Date {
func nearestHour() -> Date {
return Date(timeIntervalSinceReferenceDate:
(timeIntervalSinceReferenceDate / 3600.0).rounded(.toNearestOrEven) * 3600.0)
}
}
Upvotes: 4
Reputation:
Here's a Swift 3.0 implementation that gets the nearest hour, using a Date
extension:
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)
}
}
Upvotes: 18
Reputation: 20021
Use this method
- (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];
}
This will give you the date in next hour for the inDate
Upvotes: 9
Reputation: 143
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)
}
Upvotes: 4
Reputation:
Use the Below code. It must help for you.
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);
}
Upvotes: 0