gpt4 book ai didi

swift - 获取 NSDate 并快速将其从 24 小时格式转换为 12 小时格式

转载 作者:搜寻专家 更新时间:2023-11-01 05:58:39 25 4
gpt4 key购买 nike

我看过其他语言的这篇文章,但不是 swift。我以 2015-08-31 21:36:00 +0000 的格式保存了一个日期,我可以使用下面的代码提取日、月、年和工作日以生成 2015 年 8 月 31 日,星期一。当我尝试使用时:

let hourInt = components.hour
var hourString = String(hourInt)

它打印四个小时的差异。在这种情况下,“17”代表“21”。我如何能将其显示为 9:36 P.M.

let flags: NSCalendarUnit =  NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitHour |  NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekday | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear
let date = NSDate()
let dateFormatter: NSDateFormatter = NSDateFormatter()
let components = NSCalendar.currentCalendar().components(flags, fromDate: array.date)


let weekday = components.weekday
let weekdays = dateFormatter.weekdaySymbols
let weekdayString = weekdays[weekday-1] as! String

let month = components.month
let months = dateFormatter.monthSymbols
let monthString = months[month-1] as! String

let dayInt = components.day
var dayString = String(dayInt)

let year = components.year
let yearString = String(year)
println(weekdayString + ", " + monthString + " " + dayString + ", " + yearString)

最佳答案

您的日期字符串后缀 +0000 表示它是 UTC 时间,如果您想以 UTC 显示时间,您需要在设置日期格式器时指定它。

let dateString = "2015-08-31 21:36:00 +0000"
let df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let date = df.dateFromString(dateString) {
// now you have your date object
// to display UTC time you have to specify timeZOne UTC
df.timeZone = NSTimeZone(forSecondsFromGMT: 0)
df.dateFormat = "EEEE, MMMM dd, yyyy h:mm:ss a"
let stringFromDate = df.stringFromDate(date)
println(stringFromDate) // "Monday, August 31, 2015 9:36:00 PM"
}

关于swift - 获取 NSDate 并快速将其从 24 小时格式转换为 12 小时格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31102653/

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