本文介绍了迅速-如何将日期从上午/下午转换为24小时格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是东西.我有am/pm格式的iPhone和西班牙语(MX)的iPhone语言.当我要求日期时,我会得到类似2018-03-21 5:14:59 a的信息.米+0000是日期类型,然后我尝试将其转换为24小时格式的字符串,得到类似2018-03-20 23:14:59的字符串类型,但是当我尝试将该字符串转换为字符串时日期,我再次以am/pm格式获得相同的日期2018-03-21 5:14:59 a.米+0000我不知道该怎么办,我只想将上午/下午的日期转换为非STRING的24小时制.请帮帮我.这是我在Swift 4中的代码

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. +0000I 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")

这是我的控制台结果

    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

推荐答案

那不是 Date 的工作方式.

摘自文档

日期只是自引用日期以来一段时间的容器,它本身不携带任何格式信息.

Date is simply a container for the period of time since the reference date, it does not carry any kind of formatting information itself.

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

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

is simply converting the stringDate (2018-03-20 23:14:59 in your example) back to Date object and print is using the Dates description implementation to provide you with information about it's current value

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

So, if we instead added...

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

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

您最好的选择是不在乎.只需将值携带在 Date 对象中,然后在需要显示给用户或需要对其进行格式化时将其格式化为 String -这就是设置格式化程序的关键

Your best bet is not to care. Simply carry the value around in a Date object and format it to String when you need to display it to the user or otherwise need it formatted - that's the point of having formatters

这篇关于迅速-如何将日期从上午/下午转换为24小时格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 04:48