我有数据类型为Date的变量,我以这种格式存储日期
2018-12-24 18:00:00 UTC
我从这一天或这个月如何得到?
答案 0 :(得分:1)
如果您将“ 2018-12-24 18:00:00 UTC”另存为字符串,则可以尝试以下操作:
let dateString = "2018-12-24 18:00:00 UTC"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss 'UTC'"
guard let date = formatter.date(from: dateString) else {
return
}
formatter.dateFormat = "yyyy"
let year = formatter.string(from: date)
formatter.dateFormat = "MM"
let month = formatter.string(from: date)
formatter.dateFormat = "dd"
let day = formatter.string(from: date)
print(year, month, day) // 2018 12 24
最良好的祝愿!
答案 1 :(得分:1)
该字符串或日期类型?
如果是约会,您可以这样做:
let calanderDate = Calendar.current.dateComponents([.day, .year, .month], from: date)
这将为您提供年,月和日
答案 2 :(得分:0)
日期字符串不符合ISO8601,但是如果将ISO8601DateFormatter
替换为<space> + UTC
并使用自定义格式选项,则可以使用Z
。
从字符串中创建一个Date
,并为DateComponents
和day
获得month
let string = "2018-12-24 18:00:00 UTC"
let formatter = ISO8601DateFormatter()
let trimmedString = string.replacingOccurrences(of: "\\s?UTC", with: "Z", options: .regularExpression)
formatter.formatOptions = [.withFullDate, .withFullTime, .withSpaceBetweenDateAndTime]
if let date = formatter.date(from: trimmedString) {
let components = Calendar.current.dateComponents([.day, .month], from: date)
let day = components.day!
let month = components.month!
print(day, month)
}
答案 3 :(得分:0)
extension Date {
func get(_ components: Calendar.Component..., calendar: Calendar = Calendar.current) -> DateComponents {
return calendar.dateComponents(Set(components), from: self)
}
func get(_ component: Calendar.Component, calendar: Calendar = Calendar.current) -> Int {
return calendar.component(component, from: self)
}
}
let date = Date()
// MARK: Way 1
let components = date.get(.day, .month, .year)
if let day = components.day, let month = components.month, let year = components.year {
print("day: \(day), month: \(month), year: \(year)")
}
// MARK: Way 2
print("day: \(date.get(.day)), month: \(date.get(.month)), year: \(date.get(.year))")
答案 4 :(得分:0)
这就是我在 swift 4 中所做的。我有一个 Billing 类,其中“billDate”是一个包含日期的字段。
extension Billing:Identifiable{
func month() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM"
if let inputDate = billDate {
let month = dateFormatter.string(from: inputDate)
return month.uppercased()
}
return ""
}