繁体   English   中英

我如何将NSDate()分成几部分?

[英]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

上面的代码,每当我调用date()时,date获取韩国当前的日期值

我希望从NSDate()中刷新新值,然后将刷新值插入下面代码的变量中

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

嗯有没有方法将NSDate()分成如下代码的片段?

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

可以使用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)

您可以使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM