【问题标题】:How to format the date using NSDateFormatter in Swift for iOS?如何在 Swift for iOS 中使用 NSDateFormatter 格式化日期?
【发布时间】:2016-10-10 13:27:49
【问题描述】:

我正在尝试将此日期“2016 年 6 月 18 日。星期六”解析为“18/06/2016” 我知道这可以使用正则表达式方法来完成,但我不确定你如何使用它获得输出。

在 swift 中使用 NSDateFormatter 的方法是首选

【问题讨论】:

  • 使用NSDateFormatter 是正确的解决方案。使用正则表达式根本不是你应该这样做的。用你迄今为止尝试过的方法更新你的问题。
  • 也许阅读文档。
  • NSDateFormatter 的 Apple 文档:developer.apple.com/library/mac/documentation/Cocoa/Reference/…。如果您对NSDateFormatter 有特定问题,请编辑您的问题以包含代码和您遇到的问题。

标签: ios regex swift date nsdateformatter


【解决方案1】:

给你。

NSDateFormatter 不支持带序数指标的天数,所以你必须去掉它们。您可以使用正则表达式:

    let regex = try NSRegularExpression(pattern: "[st|nd|rd|th]", options: NSRegularExpressionOptions())
    regex.replaceMatchesInString(dateString, options: NSMatchingOptions(), range: NSMakeRange(0, 4), withTemplate: "")

然后您只需格式化日期。


完整代码:

    let dateString = NSMutableString(string: "18th of June 2016. Saturday")

    do {
        let regex = try NSRegularExpression(pattern: "[st|nd|rd|th]", options: NSRegularExpressionOptions())
        regex.replaceMatchesInString(dateString, options: NSMatchingOptions(), range: NSMakeRange(0, 4), withTemplate: "")

        let formatter = NSDateFormatter()
        formatter.locale = NSLocale(localeIdentifier: "en_US")
        formatter.dateFormat = "d' of 'MMMM y'.' EEEE"
        let date = formatter.dateFromString(dateString as String)
        formatter.dateStyle = .ShortStyle
        formatter.locale = NSLocale.currentLocale()
        let output = formatter.stringFromDate(date!)
        print(output)

    } catch let error as NSError { print(error) }


请记住,NSNumberFormatter 将根据当前的语言环境设置进行格式化。

【讨论】:

  • 由于原始日期字符串使用特定语言(英语),您需要将日期格式化程序的语言环境设置为英语语言环境。
  • @rmaddy 你是绝对正确的。我已经更新了答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多