NSDateFormatter给了我一周两个不同的日期,同一天

时间:2016-06-21 21:56:48

标签: swift swift2 nsdate nsdateformatter

有一堆约会,而我正试图获得他们一周的日子。但无论何时,即使在午夜之后,我也会循环,一周的这一天不会改变几个小时,我不知道为什么。 这是我的代码:

func parseArray(array: [HKQuantitySample])
{
let formatter = NSDateFormatter()
formatter.dateFormat = "EEEE"

for element in array
{
    let startDate: NSDate = element.startDate //example: 2015-11-13 13:30:07 +0000

    let startDateArray = String(startDate).componentsSeparatedByString(" ") // example: ["2015-11-13", "13:46:53", "+0000"]

    let startDateString = startDateArray[0] // example: 2015-11-13
    let startDateTimeString = startDateArray[1] // example: 13:58:39

    let startDateDayOfTheWeek = formatter.stringFromDate(startDate)

    print("startDate: \(startDateString), startTime: \(startDateTimeString), dayOfWeek: \(startDateDayOfTheWeek)")
}

这是我得到的:

startDate: 2015-11-12, startTime: 23:32:01, dayOfWeek: Thursday
startDate: 2015-11-12, startTime: 23:41:19, dayOfWeek: Thursday
startDate: 2015-11-12, startTime: 23:50:36, dayOfWeek: Thursday

/ *午夜* /

startDate: 2015-11-13, startTime: 00:07:35, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 00:19:19, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 00:32:20, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 00:41:37, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 00:55:34, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 01:04:51, dayOfWeek: Thursday
2016-06-21 17:39:10.446213 appleWatchHealth[1173:238873] [MC] Reading from public effective user settings.
startDate: 2015-11-13, startTime: 01:14:57, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 01:24:50, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 01:36:39, dayOfWeek: Thursday
startDate: 2015-11-13, startTime: 01:45:56, dayOfWeek: Thursday

所以即使它从12日变为13日,它仍然在星期四给我。然而,它确实在下午1点左右变为星期五:

startDate: 2015-11-13, startTime: 13:01:31, dayOfWeek: Friday

另外,我不知道最后一行意味着什么:

2016-06-21 17:39:10.446213 appleWatchHealth[1173:238873] [MC] Reading from public effective user settings.

1 个答案:

答案 0 :(得分:0)

String(startDate)使用startDate的描述,这纯粹是出于调试目的。你永远不应该将它用于最终用户看到的东西。因此,没有办法让它显示除你看到的任何东西。

每当您想要将NSDate转换为最终用户看到的内容时,都应该使用NSDateFormatter。