本文介绍了如何为日期字符串格式化 DateFormatter(NSDateFormattter)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为后面的日期字符串构造格式化程序(NSFormatter)

How to construct formatter(NSFormatter) for following Date string

Date dateString = "Sun Oct 30 2016 00:00:00 GMT+0530 (IST)"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E MMM d yyyy HH:mm:ss" // This line is not working
let dd: Date? = dateFormatter.date(from: dateString)
print("Date \(dd)") // Is returning null

API 参考:https://developer.apple.com/reference/foundation/dateformatter

推荐答案

我认为您必须告诉 DateFormatter 忽略GMT"部分,因为那样会将其丢掉.如果您有 +0530 则隐含 GMT,因此您不需要它.

I think you'll have to tell DateFormatter to ignore the 'GMT' part, because that throws it off. GMT is implied if you have +0530 though, so you don't need it.

对于这个字符串:

let dateString = "Sun Oct 30 2016 00:00:00 GMT+0530"

这种格式有效:

dateFormatter.dateFormat = "E MMM d yyyy HH:mm:ss 'GMT'x"

如果 (IST) 始终相同,您可以使用

If the (IST) is always the same, you can tell the date formatter to ignore it too by using

dateFormatter.dateFormat = "E MMM d yyyy HH:mm:ss 'GMT'x '(IST)'"

如果该部分可能会有所不同,您可能应该在解析日期之前使用 String 方法删除该部分字符串.

If that part can vary, you should probably use String methods to remove that part of the string before parsing the date.

这篇关于如何为日期字符串格式化 DateFormatter(NSDateFormattter)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-20 23:23