【问题标题】:How can i divide NSDate() into pieces?我如何将 NSDate() 分成几块?
【发布时间】:2016-05-12 20:12:56
【问题描述】:
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"

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

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

【问题讨论】:

  • 考虑重新表述问题。用 NSDateComponents 实现的不是你想要的吗?

标签: swift nsdate nsdatecomponents


【解决方案1】:

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

【讨论】:

【解决方案2】:

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

【讨论】:

  • 非常感谢!添加问题日期如何本地化?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
  • 2011-06-08
  • 1970-01-01
  • 2014-07-20
相关资源
最近更新 更多