2017-08-16 05:08:54使用swift 3将字符串转换为日期“17-Aug 13:30”

时间:2017-08-17 08:05:15

标签: ios swift swift3 nsdateformatter

我正在尝试将dateString“2017-08-17 12:08:00”转换为“17-Aug 17:38”。

func timeFromString(dateString : String)  {

    let inFormatter = DateFormatter()

    inFormatter.locale = Locale(identifier: "en_US_POSIX")
    //NSLocale(localeIdentifier: "en_US_POSIX")

    inFormatter.dateFormat = "yyyy-MM-dd HH:mm"

    let outFormatter = DateFormatter()
    outFormatter.locale = Locale(identifier: "en_US_POSIX")
    outFormatter.dateFormat = "dd-MMM hh:mm"

    let date = inFormatter.date(from: dateString)!
    let outStr = outFormatter.string(from: date)

}

我只想添加5:30。

因为日期格式化程序输入为HH:mm?所以我没有得到确切的输出?如果是,那为什么呢?

4 个答案:

答案 0 :(得分:4)

 let inFormatter = DateFormatter()

    inFormatter.locale = Locale(identifier: "en_US_POSIX")

    inFormatter.dateFormat = "yyyy-MM-dd HH:mm"

    let outFormatter = DateFormatter()
    outFormatter.locale = Locale(identifier: "en_US_POSIX")
    outFormatter.dateFormat = "dd-MMM HH:mm"

    let date = inFormatter.date(from: "2017-08-16 05:08")!
    let outStr = outFormatter.string(from: date)
    print(outStr) // 16-Aug 05:08

答案 1 :(得分:3)

输入为 yyyy-MM-dd hh:mm:ss ,输出为 dd-MMM HH:mm 。所以

    let outFormatter = DateFormatter()
    // set the input format
    outFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
    // convert your string to date
    let date = outFormatter.date(from: "2017-08-16 05:08:54")!
    // set the output format 
     outFormatter.dateFormat = "dd-MMM HH : mm"
    // convert your date to expected output string
    let outStr = outFormatter.string(from: date)
    print(outStr) // -> outputs 16-Aug 05 : 08  

答案 2 :(得分:1)

输入格式应为yyyy-MM-dd hh:mm:ss,输出格式为dd-MMM HH:mm。您始终可以在NSDateFromatter.com

中查看iOS的格式

答案 3 :(得分:1)

确保您的日期格式正确(根据您的输入字符串)。

试试这个:

    let inFormatter = DateFormatter()
    inFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let date = inFormatter.date(from: "2017-08-16 05:08:54")!
    inFormatter.dateFormat = "dd-MMM HH:mm"
    let outStr = inFormatter.string(from: date)
    print(outStr) // -> 16-Aug 05:08