如何在Swift 3中将两个字符串(日期和时间)组合成一个新日期 [英] How to combine two strings (date & time) into a new date in Swift 3

查看:86
本文介绍了如何在Swift 3中将两个字符串(日期和时间)组合成一个新日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将两个日期字符串组合成一种格式,以允许一个新的单个日期。第一个字符串是.long样式格式的字符串。第二个字符串只是一个时间字符串。值如下所示:

I am trying to combine two date strings into a format that will allow for a new single date. The first string is a .long style format string. The second string is just a time string. The values look like this:

let date = "March 24, 2017"
let time = "7:00 AM"

我需要将这些字符串组合成一个新的日期,作为iOS的快速日期。我尝试了各种DateFormatters并将字符串合并在一起,但是将.Long用于日期和.short用于时间似乎不起作用。

I Need to combine these strings to form a new date that works as iOS swift date. I have tried various DateFormatters and merging the strings together but the combination of .Long for date and .short for time does not seem to work.

推荐答案

let date = "March 24, 2017"
let time = "7:00 AM"

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MMMM dd, yyyy 'at' h:mm a"
let string = date + " at " + time                       // "March 24, 2017 at 7:00 AM"
let finalDate = dateFormatter.date(from: string)
print(finalDate?.description(with: .current) ?? "")  // "Friday, March 24, 2017 at 7:00:00 AM Brasilia Standard Time"

这篇关于如何在Swift 3中将两个字符串(日期和时间)组合成一个新日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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