How to get yyyy-mm-dd hh:mm:ss format from “2015-0

2019-06-14 18:19发布

问题:

I have stuck in issue in which i have to convert date format is 2015-06-26T00:10:00+01:00 into yyyy-mm-dd hh:mm:ss please give me some idea how to do this?

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)")

and the out put is start time : nil

回答1:

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.

See: ICU Formatting Dates and Times )



回答2:

Have you tried this one too?

var formatter: NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss"
let dateTimePrefix: String = formatter.stringFromDate(NSDate())


回答3:

Please try this:

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)
}