NSDateFormatter dateFormatFromTemplate问题

时间:2015-08-02 12:29:03

标签: ios swift nsdateformatter

我需要恢复数小时和分钟的本地化格式。小时工作按预期工作但分钟返回" m"?为什么不回来" mm"?

let locale = NSDateFormatter().locale

NSDateFormatter.dateFormatFromTemplate("HH", options: 0, locale:locale)
//Returns "HH" in US English and "H时" in Chinese (Simplified)

NSDateFormatter.dateFormatFromTemplate("mm", options: 0, locale:locale)
//Returns "m" for both???

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用NSDateComponents

let date: NSDate = NSDate()
let calendar = NSCalendar.currentCalendar()

let components = calendar.components(NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute, fromDate: date)

components.hour = 20
components.minute = 10

if let newDate = calendar.dateFromComponents(components) {
    let dateFormatter = NSDateFormatter()
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
    dateFormatter.stringFromDate(newDate)
}

这里再次作为检索所需值的函数:

func formattedTimeString(unitToSet: NSCalendarUnit, selectedValue: Int, template: String) -> String?
{
    let date: NSDate = NSDate()
    let calendar = NSCalendar.currentCalendar()

    let components = calendar.components(NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute, fromDate: date)

    if unitToSet == .CalendarUnitHour
    {
        components.hour = selectedValue
    } else
    {
        components.minute = selectedValue
    }

    if let newDate = calendar.dateFromComponents(components) {
        let dateFormatter = NSDateFormatter()

        dateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate(template, options: 0, locale: NSLocale.currentLocale())

        return dateFormatter.stringFromDate(newDate)
    }

    return nil
}

if let hours: String = formattedTimeString(.CalendarUnitHour, 22, "HH")
{
    println(hours) // prints 22
}

if let minutes: String = formattedTimeString(.CalendarUnitMinute, 33, "mm")
{
    println(minutes) // prints 33
}

如果您还有其他问题,也可以Gist使用。