我使用API,其中一个参数的类型为Date,格式为“dd.MM.yyyy”。
我无法转换它。我为Date创建了一个扩展,我尝试以这种方式实现它:
extension Date {
var shortDate: Date {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
let strDate = formatter.string(from: self)
let modifiedDate = formatter.date(from: strDate)
return modifiedDate!
}
}
我称之为:
let day = Date().shortDate
不幸的是,它不起作用,它看起来像这样:
2017-06-18 21:00:00 +0000
我该如何解决?
答案 0 :(得分:2)
根据我的理解,您需要使用以"dd.MM.yyyy”
格式表示日期的API进行通信。以下是您需要实现的简单功能:
class MyAPIFunctions
{
static let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
// make sure the following are the same as that used in the API
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale.current
return formatter
}()
class func shortString(fromDate date: Date) -> String {
return formatter.string(from: date)
}
class func date(fromShortString string: String) -> Date? {
return formatter.date(from: string)
}
}
我已将formatter
声明为单独的常量,以节省每次调用重新初始化的开销。
添加这些功能后,您可以按如下方式向API发送日期:
let today = Date()
let todayString = MyAPIFunctions.shortString(fromDate: today)
// send todayString to API
要将API中的字符串转换为Date对象,
let apiString = "17.07.2017"
guard let apiDate = MyAPIFunctions.date(fromShortString: apiString) else {
// deal with formatting error here
return
}
// work with apiDate object
答案 1 :(得分:0)
let date = Date.init()
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
formatter.locale = NSLocale(localeIdentifier: "en_US") as Locale!
let strdate1 = formatter.string(from: date as Date)
print(strdate1)