如何将时间字符串转换为 NSDate? [英] How to convert time String into NSDate?
本文介绍了如何将时间字符串转换为 NSDate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将时间字符串(24 小时格式)转换为 NSDate 进行比较?
How can I convert time string (in 24h format) into NSDate for comparison?
我在这里得到零和错误的 NSDate:
I get nil and wrong NSDate here:
let a = "5:46"
let b = "24:30"
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
dateFormatter.dateFormat = "k:mm" // k = Hour in 1~24, mm = Minute
let outputA = dateFormatter.dateFromString(a)
let outputB = dateFormatter.dateFromString(b)
println("A: \(outputA) B: \(outputB)")
然后我得到
A: Optional(1999-12-31 20:46:00 +0000) B: nil
当我想得到
A: 5:46 AM B: 00:30 AM
或
A: 05:46 B: 24:30
只要我能比较这两个小时,哪种 NSDate 格式并不重要.
It doesn't really matter which NSDate format as long as I can compare those two hours.
推荐答案
在日期格式中添加NSTimeZone
.
let a = "5:46"
let b = "24:30"
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
dateFormatter.dateFormat = "k:mm" // k = Hour in 1~24, mm = Minute
let timeZone = NSTimeZone(name: "UTC")
dateFormatter.timeZone=timeZone
let outputA = dateFormatter.dateFromString(a)
let outputB = dateFormatter.dateFromString(b)
println("A: \(outputA) B: \(outputB)")
输出是:
Printing description of outputA:
2000-01-01 05:46:00 +0000
Printing description of outputB:
2000-01-01 00:30:00 +0000
这篇关于如何将时间字符串转换为 NSDate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文