且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NSDate swift的日期字符串

更新时间:2022-06-23 05:30:25

你必须使用 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)