将日期组件(整数)转换为字符串 [英] Converting Date Components (Integer) to String

查看:29
本文介绍了将日期组件(整数)转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码接受一个 NSDate 并读取年、月和日,然后将它们串在一起作为一个整数.我接下来想把这个 Int 转换成一个字符串,这样就可以插入到一个 URL 字符串中,但是没有成功:

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)

然而,他们都告诉我Int 不能转换为 String",或者,带有!"在as"之后,Int 转换为 String 将永远失败".有没有人有办法解决这个问题?

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?

推荐答案

你的第一个 - 几个 - 尝试是正确的

Your first - several - attempt is correct

let dateString = "\(dateInt)"

或复杂"版本

let dateString = String(stringInterpolationSegment: dateInt)

但您可能希望连接字符串值而不是执行数学加法,然后使用 zaph 答案的语法.

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

这篇关于将日期组件(整数)转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆