LoginSignup
6
5

More than 5 years have passed since last update.

入力された時間を5分単位に丸めるメソッド

Last updated at Posted at 2013-03-04
@implementation NSDate (NSDateRounding)
- (NSDate *)dateByRoundingUpToFiveMinutes
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"m"];
    int ref = [[formatter stringFromDate:self] intValue];//基準分を切り抜き

    if(ref % 5 == 0) return self;

    float def = round(ref * .1f) * 10;//0.1かけてから四捨五入して10かける
    if(def < ref) def += 5;//元値より小さければ5足す
    return [self dateByAddingTimeInterval:60*(def - ref)];//基準分から差分をひいて秒数に変換
}
@end
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5