我目前的时区 UTC-05:00 。当我调用函数NSDate(timeIntervalSince1970:0)
时,它返回" 1969年12月31日,晚上7点和#34;
let date = NSDate.init(timeIntervalSince1970: 0) // "Dec 31, 1969, 7:00 PM"
print(date) // "1970-01-01 00:00:00 +0000\n"
我读到了这个How to get NSDate day, month and year in integer format?但问题是,由于5小时的时差,我总是得到1969-12-31。
let calendar = NSCalendar.currentCalendar()
calendar.getEra(&era, year:&year, month:&month, day:&day, fromDate: date)
year // 1969
month // 12
day // 31
var hour = 0, minute = 0, second = 0
calendar.getHour(&hour, minute: &minute, second: &second, nanosecond: nil, fromDate: date)
hour // 19
minute // 0
second // 0
有没有办法在当前时区获取当前年,月,日等值。我在这里寻找的是:
year // 1970
month // 01
day // 01
答案 0 :(得分:2)
timeIntervalSince1970
初始化程序为您(如文档所示)提供了NSDate
,这是自1970年1月1日00:00:00 以来的一些秒数,而不是您当地的时区。您获得的结果是正确的,因为它们显示了您当地时区与此时间的偏差。你传递的是0,所以你在1970年1月1日00:00:00 UTC ,然后NSCalendar
给你相同的日期和时间在你当地的时区
如果您想在当地时区的1970年1月1日00:00:00获得该日期,则需要专门从NSCalendar
申请该日期:
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.localTimeZone()
let date = calendar.dateWithEra(1, year: 1970, month: 1, day: 1, hour: 0, minute: 0, second: 0, nanosecond: 0)
calendar.getEra(&era, year:&year, month:&month, day:&day, fromDate: date!)
year // 1970
month // 1
day // 1
这不是timeIntervalSince1970
的0偏移量。如果您检查,您将看到结果对应于您的时区与UTC的偏移量:
date?.timeIntervalSince1970 // 25200, for me
答案 1 :(得分:1)
这将返回当前日期ex。 02/26/2016
// Format date so we may read it normally
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/M/yyyy"
let currentDate = String(dateFormatter.stringFromDate(NSDate()))
Swift 3.0
NSDateFormatter
> DateFormatter
&& NSDate
> Date
let df = DateFormatter()
df.timeZone = .current
df.dateStyle = .medium
df.timeStyle = .short
df.dateFormat = "dd/M/yyyy"
let currentDate = df.string(from: Date())