如何使用 Swift 4.0 获取简短的本地日期/时间格式? [英] How do I get the short, local date/time format with Swift 4.0?

查看:30
本文介绍了如何使用 Swift 4.0 获取简短的本地日期/时间格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码(swift 4.0,Xcode 10.2)打印日期(例如生日):

I am trying to print a date (e.g. a birthdate) using the following code (swift 4.0, Xcode 10.2):

    let formatter = DateFormatter()
    formatter.timeStyle = .short
    formatter.dateStyle = .short
    formatter.locale = Locale(identifier: "en_US")
    formatter.dateFormat = "yyyy/MM/dd HH:mm"
    let DOB = formatter.date(from: "2019/05/01 22:30")

当我收到打印(DOB)时,2019-05-02 05:30:00 +0000"

when print(DOB) I got, "2019-05-02 05:30:00 +0000"

看起来本地、.short 设置都没有影响结果.

It looks like none of the Local, .short settings affected the results.

怎么了.如何简单地打印:2019/05/01 22:30"?

What's wrong. How do I get to simply print: "2019/05/01 22:30"?

推荐答案

您当前正在做的是将字符串转换为 Date.Date 不包含有关它们如何显示的信息.它们以相同的方式打印:2019-05-02 05:30:00 +0000.

What you are currently doing is converting a string to a Date. Dates don't contain information about how they are displayed. They are printed all the same way: 2019-05-02 05:30:00 +0000.

Strings 有格式,因此您应该使用日期格式化程序将刚刚获得的 Date 转换回字符串.基本上,您有两个格式化程序:一个用于将字符串转换为日期,另一个用于将日期转换回字符串

Strings have formats, so you should convert the Date you just got, back to a string using a date formatter. Basically, you have two formatters: one for converting the string to a date, and another for converting the date back to a string

let stringToDateformatter = DateFormatter()
stringToDateformatter.dateFormat = "yyyy/MM/dd HH:mm"
let DOB = stringToDateformatter.date(from: "2019/05/01 22:30")

let dateToStringFormatter = DateFormatter()
dateToStringFormatter.timeStyle = .short
dateToStringFormatter.dateStyle = .short
dateToStringFormatter.locale = Locale(identifier: "en_US")
let DOBString = dateToStringFormatter.string(from: DOB!)
print(DOBString) // 5/1/19, 10:30 PM

这篇关于如何使用 Swift 4.0 获取简短的本地日期/时间格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆