将日期转换为字符串并使用它来修剪它的问题



我尝试将日期转换为字符串,然后对其进行修剪。不知何故,Xcode 不接受beforeConv作为字符串。我一无所知,还尝试了其他方法将日期转换为字符串,例如不起作用的formatter.sring(from: date)

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let date = Date()
let beforeConv = "(date)"
let start = beforeConv(beforeConv.startIndex, offsetBy: 11) // Cannot call value of non-function type 'String'
let end = beforeConv(beforeConv.endIndex, offsetBy: -12)    // Cannot call value of non-function type 'String'
let range = start..<end
let cleanTime = beforeConv[range]
let postZone = String(cleanTime)

为了提取日分量而将Date转换为String是非常笨拙的(而且没有必要(。幸运的是,Swift 提供了一个DateComponents来处理包含日期的组件。以下是它的工作原理:

let date = Date()
let dateParts = Calendar.current.dateComponents([.day, .month], from: date)
let day = dateParts.day // this is an optional Int?
let month = dateParts.month

对于单个组件,您还可以执行以下操作:

// this is Int
let day = Calendar.current.component(.day, from: date) 

最新更新