[英]dateFromString() returning wrong date swift 3.0
i am passing "01/12/2017" in the fromDate.text(textfield), but receiving unexpected output. 我在fromDate.text(textfield)中传递“01/12/2017”,但收到意外的输出。
let formatter = DateFormatter.init()
formatter.dateFormat = "dd/mm/yyyy"
startDate = formatter.date(from: fromDate.text!)
print("startDate = \(startDate)")
output is : 31/12/2016 输出是:2016年12月31日
The format of date should be dd/MM/yyyy
not dd/mm/yyyy
. 日期格式应为
dd/MM/yyyy
而不是dd/mm/yyyy
。 The mm
indicates the minutes and MM
indicates the month. mm
表示分钟, MM
表示月份。
And also add the below line in your code 并在代码中添加以下行
formatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
This line of code set time zone. 这行代码设置了时区。 If you not, then you get
30/11/2017
in output. 如果你没有,那么你得到
30/11/2017
的输出。
The reason behind this is when string date not contain time then formatter assume that it is midnight and you also not given the timezone so it will take current timezone. 这背后的原因是当字符串日期不包含时间时格式化程序假设它是午夜而你也没有给出时区所以它将占用当前时区。
It has to be dd/MM/yyyy
dateformat. 它必须是
dd/MM/yyyy
dateformat。 MM
in capital. MM
在首都。
func convertToString(of dateTo: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy" //Your New Date format as per requirement change it own
let newDate: String = dateFormatter.string(from: dateTo) //pass Date here
print(newDate) //New formatted Date string
return newDate
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.