Gundam Gundam - 6 months ago 26
Swift Question

How can i divide NSDate() into pieces?

func date() -> String {
return NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.MediumStyle)
}

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


above code, date obtain korean current value of date every time that i call date()

I'll hope to have refresh new value from NSDate(), and so insert refresh new value into varibles like below code

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


hmmm Are there methods to divide NSDate() into pieces like below code?

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

Answer

You can use the 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)