我遇到了问题,我必须将日期格式转换为2015-06-26T00:10:00 + 01:00进入yyyy-mm-dd hh:mm:ss 请告诉我如何做到这一点?
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let startTimeString = "2015-06-26T00:10:00+01:00"
let startTime = formatter.dateFromString(startTimeString)
print("start time : \(startTime)")
,输出是开始时间:nil
答案 0 :(得分:7)
let startTimeString = "2015-06-26T00:10:00+01:00"
// First convert the original formatted date/time to a string:
let deFormatter = NSDateFormatter()
deFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let startTime = deFormatter.dateFromString(startTimeString)
print(startTime!) // 2015-06-25 23:10:00 +0000
// Note that `println` use the `description` method which defaults to UTC.
// Then convert the date/time to the desired formatted string:
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let timeString = formatter.stringFromDate(startTime!)
print(timeString) // 2015-06-25 19:10:00
// Note that `NSDateFormatter` defaults to the local time zone.
答案 1 :(得分:2)
你也试过这个吗?
var formatter: NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss"
let dateTimePrefix: String = formatter.stringFromDate(NSDate())
答案 2 :(得分:1)
对于Swift 5
let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateTime: String = formatter.string(from: Date())
答案 3 :(得分:0)
请试试这个:
let dateString = "2015-06-26T00:10:00+01:00"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxxx"
if let dateFromString = formatter.date(from: dateString) {
formatter.dateFormat = "yyyy-MM-dd HH:mm" //which format is needed
let stringFromDate = formatter.string(from: dateFromString)
print(stringFromDate)
}