Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Date Components (Integer) to String

Tags:

swift

xcode6

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?

like image 538
ButtonMasterBot Avatar asked Feb 17 '26 02:02

ButtonMasterBot


2 Answers

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)
like image 189
zaph Avatar answered Feb 19 '26 23:02

zaph


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.

like image 40
vadian Avatar answered Feb 20 '26 01:02

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!