gpt4 book ai didi

ios - NSDateFormatter dateFormatFromTemplate 问题

转载 作者:行者123 更新时间:2023-11-28 09:01:57 24 4
gpt4 key购买 nike

我需要取回小时和分钟的本地化格式。时间按预期工作,但分钟返回“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???

最佳答案

您是否尝试过使用 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 ,如果您还有其他问题。

关于ios - NSDateFormatter dateFormatFromTemplate 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31771885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com