如何将基于十进制的时间转换为 NSDate?

How to convert decimal-based time to NSDate?

我有时间表示为双打。例如:

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

如何将双打转换为今天的 NSDate?

今天午夜使用这个答案: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]];

然后,一旦您确定了午夜时间,我们将使用 addTimeInterval 从您的十进制值中添加秒数。

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];

应该成功!

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)!

从今天午夜开始,加上您的小时数:

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

(大多数小数不是用Double精确表示的, 这就是时间间隔四舍五入到秒的原因。)

Examples/test 例:

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