NSDate swift的日期字符串
我正在使用日期字符串填充数组,我想查看该日期字符串并检查日期是今天还是昨天。日期字符串可能如下所示:
i'm having an array fill with date string, which i would like to go through and check whether the date is today or yesterday. The date string could look like following:
2015-04-10 22:07:00
到目前为止,我已经尝试过使用dateFormatter转换它,但它一直返回nil
So far i've tried just to convert it using dateFormatter, but it keeps returning nil
var dateString = arrayNews[0][0].date as NSString
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
var date = dateFormatter.dateFromString(dateString as String)
println(date)
sudo代码我想看起来像这样
the sudo code i would like to look something like this
if dateString == currentDate
date = "Today, hh:mm"
else if dateString == currentDate(-1)
date = "Yesterday, hh:mm
else
date = dd. MM, hh:mm
在else语句中日期可能为1. April ,12:00
in the else statement the date could be 1. April, 12:00
我如何实现这样的逻辑?
How can i achieve such a logic?
没有逻辑
func getDate(dateStr:String, format:String = "yyyy-MM-dd HH:mm:ss") -> NSString {
var dateFmt = NSDateFormatter()
dateFmt.timeZone = NSTimeZone.defaultTimeZone()
dateFmt.dateFormat = format
let newsDate = dateFmt.dateFromString(dateStr)!
let date = NSDate();
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone()
let localDate = dateFormatter.stringFromDate(date)
return ""
}
你必须使用 yyyy-MM-dd HH:mm:ss
而不是 yyyy-MM-dd hh:mm:ss
- HH:24h格式
- hh:12h格式(带AM / PM)
使用dateFormatter注意,默认情况下,它使用localtime zone。 println()
显示GMT时间的值,由NSDate持有。
Pay attention with dateFormatter, by default, it use localtime zone.
println()
shows the value for GMT time, which is hold by NSDate.
这意味着,在不指定时区的情况下,当您将字符串 2015-04-10 22:07:00
转换为NSDatetime时,它会返回一个数据,即您当地时区的时间是 2015-04-10 22:07:00 。由于 NSDate
在GMT中保存日期时间,当您使用 NSDate 的值时,您将看到不同的值code>的println()。
It means, without specifying timezone, when you convert your string 2015-04-10 22:07:00
to NSDatetime, it return a data which is the time at your local time zone is 2015-04-10 22:07:00. As NSDate
holds date time in GMT, you will see a different value when you show the value of that NSDate
with println()
.
如果你的时区是格林尼治标准时间+2(早于格林尼治标准时间2小时),当你的位置是22h:07时,格林尼治标准时间是20小时:07。当你在 NSDate
上调用 println()
时,你会看到2015-04-10 20:07:00
If your timezone is GMT+2 (2h earlier than GMT), when it's 22h:07 in your place, the GMT time is 20h:07. When you call println()
on that NSDate
, you see 2015-04-10 20:07:00
比较2 NSDate:
To compare 2 NSDate:
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
let compareResult = calendar?.compareDate(date, toDate: date2, toUnitGranularity: NSCalendarUnit.CalendarUnitDay)
if (compareResult == NSComparisonResult.OrderedSame) {
println("yes")
} else {
println("no")
}
//昨天使用NSCalendar获取:
//to get yesterday, using NSCalendar:
let yesterday = calendar?.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: -1, toDate: date, options: NSCalendarOptions.MatchStrictly)