不正确的字符串到日期转换 swift 3.0 [英] incorrect string to date conversion swift 3.0

查看:31
本文介绍了不正确的字符串到日期转换 swift 3.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将字符串中的 10/24 12:00 PM 格式转换为日期格式中的等效格式.我正在使用以下代码:

I am converting a format like 10/24 12:00 PM in string to the equivalent in Date format. I am using the following code:

let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd hh:mm aa"

   self.dateCompleted = dateFormatter.date(from: self.DeliverBy!)

dateCompleted 是一个 Date 变量,而 self.DeliveryBy 是一个 String 变量.

dateCompleted is a Date variable whereas self.DeliveryBy is a String variable.

我得到了类似 2000-10-24 17:00:00 UTC 的输出,而它应该是类似 2017-10-24 12:00:00 UTC 的输出.我做错了什么吗?

I am getting an output like 2000-10-24 17:00:00 UTC where as it should be something like 2017-10-24 12:00:00 UTC. Am i doing something wrong?

我提到了 http://userguide.icu-project.org/formatparse/datetime

推荐答案

您的日期字符串未指定年份,因此从默认日期确定.您可以做的是设置默认日期为(开始的)当天:

Your date string does not specify a year, which is therefore determined from the default date. What you can do is to set the default date to the (start of the) current day:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd hh:mm aa"
dateFormatter.defaultDate = Calendar.current.startOfDay(for: Date())
if let dateCompleted = dateFormatter.date(from: "10/24 12:00 PM") {
    print(dateCompleted) // 2017-10-24 10:00:00 +0000
}

(我在欧洲/柏林时区,因此打印 12:00 PM格林威治标准时间 10:00.)

(I am in the Europe/Berlin timezone, therefore 12:00 PM is printed as 10:00 GMT.)

这篇关于不正确的字符串到日期转换 swift 3.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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