2016-05-12 46 views
1
func date() -> String { 
return NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.MediumStyle) 
} 

var date = date() // 2016. 5. 13. 오전 4:45:16 

上面的代碼,日期獲取日期的韓國電流值每次我打電話日期()時間我怎樣才能把NSDate()分成幾塊?

我希望從NSDate的()有刷新新的價值,所以插入刷新新的價值到像可變因素下面的代碼

var yearMonDay = "2016. 5. 13" 
var hourMinSec = "오전 4:45:16" 

hmmm是否有方法將NSDate()分成如下面的代碼段?

yearMonDay = NSDate().?? // refresh date "year: month: day" 
hourMinSec = NSDate().?? // refresh date "am/fm hour:minute:second 
+0

缺點思想者重新提出了這個問題。是不是你想實現你可以用NSDateComponents做什麼? – catalandres

回答

1

可以使用NSDateFormatterStyle

// get the current date and time 
let currentDateTime = NSDate() 

// initialize the date formatter and set the style 
let formatter = NSDateFormatter() 

// October 26, 2015 
formatter.timeStyle = NSDateFormatterStyle.NoStyle 
formatter.dateStyle = NSDateFormatterStyle.LongStyle 
formatter.stringFromDate(currentDateTime) 

// 6:00:50 PM 
formatter.timeStyle = NSDateFormatterStyle.MediumStyle 
formatter.dateStyle = NSDateFormatterStyle.NoStyle 
formatter.stringFromDate(currentDateTime) 
+0

非常感謝你! 添加問題 日期如何本地化? – Gundam

2

分裂部件,例如小時可以使用的NSCalendar

let today  = NSDate() 
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)! 
let components = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: today) 
print("\(components.month)  \(components.day)  \(components.year)") 
print("\(components.hour)  \(components.minute)  \(components.second)") 

組件隨着NSDate的格式,你可以找到的名稱來完成

let formatter = NSDateFormatter() 
let monthName = formatter.monthSymbols[components.month-1] 
print(monthName) 
+0

哇!好答案! 非常有用的提示 非常感謝你! – Gundam

+0

'NSDate(timeIntervalSinceNow:0)'???請使用'NSDate()'。除此之外,你可以使用NSDateFormatter獲取月份名稱檢查http://stackoverflow.com/a/27369380/2303865 –