日期输出不同。因此,无法正确比较

时间:2016-08-31 07:16:03

标签: swift nsdate

这是我的代码。请先看一下

import UIKit

var expireDate : Double = 1472647093

var date = NSDate(timeIntervalSince1970: expireDate)
print("Date : \(date)")

let current_date = NSDate()

if date.compare(current_date) == NSComparisonResult.OrderedDescending{
    print("is Greater than current date")
}else if date.compare(current_date) == NSComparisonResult.OrderedAscending{
    print("is Less than current date")
}else{
    print("Same")
}

这是操场上的输出: enter image description here

我真的不知道为什么"日期:"输出与日期变量不同。我的服务器在unix时间戳中发送一个过期日期格式,格式为长格式。我真的需要将它与当前日期进行比较。实际上

Aug 31, 2016, 7:08 PM // It has correct day/month/year but incorrect time

2016-08-31 12:38:13 +0000\n // has all correct time and date that the server send which was 12:38PM

那么,为什么我的日期超过当前日期呢?为什么是晚上7:08而不是12:38 PM

任何帮助?

更新: enter image description here

2 个答案:

答案 0 :(得分:2)

由于Aug 31, 2016, 7:08 PM是您当前的时间戳,因此您没有错误的日期,而在您使用时区UTC打印时。当您比较UTC中的日期时,您没有任何问题。

答案 1 :(得分:0)

My above question has nothing wrong with it. I'm just misunderstood with the timezone or standard that I am dealing with. The server already send me expire date with my timezone locale in UTC standard format.

So,I don't need to change that expire date according to my current time zone.

All I have to do is get my current time,change it to UTC format using my current timezone. And compare server expire_date and current_date. Mission Accomplish.

// Using Expire Date
var expireDate : NSTimeInterval = 1472689452 // 00:24 AM UTC
var date = NSDate(timeIntervalSince1970: expireDate) // Since January 1 1970 Convert to NSDate

// Then I change this time format to UTC String without adding any timezone because its already included
var df_utc = NSDateFormatter()
df_utc.timeZone = NSTimeZone(name: "UTC")
df_utc.dateFormat = "yyyy.MM.dd G 'at' HH:mm:ss zzz"

// Get the expire date string by formatting it in UTC
var ts_utc_string : NSString = df_utc.stringFromDate(date)

// Getting current time of mine
var local_date = NSDate()
var df_local = NSDateFormatter()
df_local.timeZone = NSTimeZone(name: "MMT") // then use my locale to add that current time UTC [MMT +6:30]
df_local.dateFormat = "yyyy.MM.dd G 'at' HH:mm:ss zzz"
var ts_local_string : NSString = df_local.stringFromDate(local_date)

// Compare
if ts_local_string.compare(ts_utc_string as String) == NSComparisonResult.OrderedDescending{
    print("CurrentTime is Greater than Expire Time")
}else if ts_local_string.compare(ts_utc_string as String) == NSComparisonResult.OrderedAscending{
    print("CurrentTime is Less than Expire Time")
}else{
    print("Same")
}

Here is the output : enter image description here

For those who are still seeking for such problem like me, UTC was just a standard for timezone. If you need to compare it with your timezone, you just need to change your current time according to your country timezone.