如何在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"