【发布时间】:2020-09-16 08:24:14
【问题描述】:
我对编程很陌生,我正在使用具有日期字段的数据库。字段中的所有数据都保存为 yyyymmdd 格式的字符串。我想将它们转换为更友好的东西以显示给用户。我创建了以下结构和函数来做到这一点。它有效,但我想知道是否有任何更简单的想法。
struct MyDate {
var day: String
var month: String
var year: String
}
func ConvertToUsefullDate (_ date: String) -> MyDate {
var myDate: MyDate = .init(day: "", month: "", year: "")
myDate.year =
String(date[date.index(date.startIndex, offsetBy: 0)]) +
String(date[date.index(date.startIndex, offsetBy: 1)]) +
String(date[date.index(date.startIndex, offsetBy: 2)]) +
String(date[date.index(date.startIndex, offsetBy: 3)])
myDate.month =
String(date[date.index(date.startIndex, offsetBy: 4)]) +
String(date[date.index(date.startIndex, offsetBy: 5)])
myDate.day =
String(date[date.index(date.startIndex, offsetBy: 6)]) +
String(date[date.index(date.startIndex, offsetBy: 7)])
switch myDate.month {
case "01": myDate.month = "Jan"
case "02": myDate.month = "Feb"
case "03": myDate.month = "Mar"
case "04": myDate.month = "Apr"
case "05": myDate.month = "May"
case "06": myDate.month = "Jun"
case "07": myDate.month = "Jul"
case "08": myDate.month = "Aug"
case "09": myDate.month = "Sep"
case "10": myDate.month = "Oct"
case "11": myDate.month = "Nov"
case "12": myDate.month = "Dec"
default: myDate.month = "Invalid"
}
return myDate
}
谢谢 - 欢迎所有反馈。
丹尼尔
【问题讨论】:
标签: swift string date character string-parsing