TruMan1
TruMan1

Reputation: 36088

How to convert decimal-based time to NSDate?

I have times that are represented as doubles. For example:

8:00am is 8.00
1:30pm is 13.50
6:15pm is 18.25
11:20pm is 23.333

How can I convert the doubles into an NSDate of today?

Upvotes: 0

Views: 396

Answers (3)

Martin R
Martin R

Reputation: 539745

Start with midnight of today and add your amount of hours:

func dateFromDecimalHours(hours: Double) -> NSDate {
    let midnight = NSCalendar.currentCalendar().startOfDayForDate(NSDate())
    let date = midnight.dateByAddingTimeInterval(round(hours * 3600.0))
    return date
}

(Most decimal fractions are not represented exactly by a Double, that's why the time interval is rounded to seconds.)

Examples/test cases:

let fmt = NSDateFormatter()
fmt.dateFormat = "dd/MM/yyyy hh:mm.ss a"

let d1 = dateFromDecimalHours(18.25)
println(fmt.stringFromDate(d1))    // 07/05/2015 06:15.00 pm

let d2 = dateFromDecimalHours(23.3333)
println(fmt.stringFromDate(d2))    // 07/05/2015 11:20.00 pm

let d3 = dateFromDecimalHours(1.0 + 23.0/60.0 + 45.0/3600.0)
println(fmt.stringFromDate(d3))    // 07/05/2015 01:23.45 am

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236360

let input = 13.50

let hour = Int(input)
let minute = Int((input - Double(Int(input))) * 60)

let resultDate = NSCalendar.currentCalendar().dateBySettingHour(hour, minute: minute, second: 0, ofDate: NSDate(), options: nil)!

Upvotes: 2

Sam
Sam

Reputation: 320

Get midnight today using this answer : How can I get an NSDate object for today at midnight?

NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSUInteger preservedComponents = (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit);
date = [calendar dateFromComponents:[calendar components:preservedComponents fromDate:date]];

Then once you have the time at midnight, we will use addTimeInterval to add on the seconds from your decimal value.

int hoursToAdd = (int)timeDecimal;
int minutesToAdd = timeDecimal - hoursToAdd; 
int secondsFromHours = hoursToAdd*60*60;
int secondsFromMinutes = minutesToAdd*60;
int totalSeconds = secondsFromHours + secondsFromMinutes;
NSDate *newDate = [date addTimeInterval:totalSeconds];

Should do the trick!

Upvotes: 1

Related Questions