[英]How to get year month day from NSDate for the current timezone
我當前在時區UTC-05:00 。 當我調用函數NSDate(timeIntervalSince1970:0)
,它返回“ 1969年12月31日,下午7:00”
let date = NSDate.init(timeIntervalSince1970: 0) // "Dec 31, 1969, 7:00 PM"
print(date) // "1970-01-01 00:00:00 +0000\n"
我讀到有關如何獲取NSDate日,月和年的整數格式的信息? 但是問題在於,由於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
timeIntervalSince1970
初始化程序為您提供(如所記錄) NSDate
,該時間是自1970年1月1日UTC時間00:00:00以來的秒數,而不是您當地的時區。 您得到的結果是正確的,因為它們顯示的是當地時區與該時間的偏移量。 您傳遞的是0,所以您將在UTC 1970年1月1日00:00:00獲得,然后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
這將返回當前日期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()))
斯威夫特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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.