0

Here is the thing. I have my iPhone in am/pm format and iPhone Language in Spanish(MX). when I ask for the date, I get something like 2018-03-21 5:14:59 a. m. +0000 and it's a date type, then I try to convert it to string in 24hours format, and I get something like 2018-03-20 23:14:59 and it's a String type, BUT when I try to convert that string into date, I get the same date in am/pm format again 2018-03-21 5:14:59 a. m. +0000 I don't know what else to do, all I want is convert my am/pm date to 24hours date NOT STRING. Help me please. Here is my code in Swift 4

    let todayDate = Date()
    print("todayDate: \(todayDate)")
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
    let stringDate = dateFormatter.string(from: todayDate)
    print("stringDate: \(stringDate)")
    let dateFromString = dateFormatter.date(from: stringDate)
    print("dateFromString: \(dateFromString!)\n\n\n")

this is my console results

    todayDate: 2018-03-21 5:14:59 a. m. +0000
    stringDate: 2018-03-20 23:14:59
    dateFromString: 2018-03-21 5:14:59 a. m. +0000
4

1 回答 1

4

我想要的只是将我的上午/下午日期转换为 24 小时日期而不是字符串

这不是如何Date工作的。

从文档

日期值表示相对于绝对参考日期的时间间隔。

Date只是自参考日期以来的一段时间的容器,它本身不携带任何格式信息。

let dateFromString = dateFormatter.date(from: stringDate)
print("dateFromString: \(dateFromString!)\n\n\n")

只是将stringDate(2018-03-20 23:14:59在您的示例中) 转换回Dateobject 并print使用Datesdescription实现为您提供有关其当前值的信息

所以,如果我们改为添加......

print("dateFromString: \(dateFormatter.string(from: dateFromString!))\n\n\n")

它会打印2018-03-21 16:44:17

你最好的选择是不在乎。只需在Date对象中携带值并将其格式化为String您需要将其显示给用户或需要对其进行格式化 - 这就是使用格式化程序的重点

于 2018-03-21T05:45:57.413 回答