Converting Date Components (Integer) to String

瘦欲@ 提交于 2020-01-05 22:46:13

问题


My code takes an NSDate and reads year, month, and day, then strings them together as a single integer. I next want to convert this Int to a String, so that it can be inserted into a URL String, but without success:

let calendarUnits: NSCalendarUnit = .CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear
let components = NSCalendar.currentCalendar().components(calendarUnits, fromDate: dateToBeExamined)
var dateInt = components.year
dateInt += components.day
dateInt += components.month
var dateString = dateInt as! String

I have tried several methods, including the following:

"\(dateInt)"
dateInt.description
dateInt as String
String(dateInt)

However, all of them tell me that "Int is not convertible to String", or, with an "!" after the "as", that "Int cast to String will always fail". Does anyone have a way around this?


回答1:


Your first - several - attempt is correct

let dateString = "\(dateInt)"

or the "sophisticated" version

let dateString = String(stringInterpolationSegment: dateInt)

Edit: but you might want to concatenate the string values rather than performing a mathematical addition, then use the syntax of the answer of zaph.




回答2:


let dateString = "\(components.year)\(components.day)\(components.month)"
println("dateString: \(dateString)")

Output:

dateString: 2015118

or

let dateString = String(components.year) + String(components.day) + String(components.month)


来源:https://stackoverflow.com/questions/31948226/converting-date-components-integer-to-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!