【问题标题】:How can a weekday string return from NSDateComponents by passing an integer?如何通过传递整数从 NSDateComponents 返回工作日字符串?
【发布时间】:2015-06-06 17:06:05
【问题描述】:

假设我通过整数值知道日期,但我想在用户的语言环境中获取工作日的字符串值。可以在没有日期对象的情况下使用NSDateComponents 通过传递整数以某种方式返回日期(例如星期一)吗?

目前我正在使用带有星期几的字典,但就用户位置而言,这显然远非理想。

【问题讨论】:

    标签: ios nsdatecomponents nsdatecomponentsformatter


    【解决方案1】:

    获取星期几的数字,然后使用 NSDateFormatter 的 weekdaySymbols(或 shortWeekdaySymbols)获取工作日名称的 NSArray。

    NSDateFormatter 需要设置有效的 NSCalendar/NSLocale,否则不需要“知道”当前日期/时间是什么。

    【讨论】:

      【解决方案2】:

      Hot Licks 的回答很棒。投票赞成。

      要查看只需要一行时写 10 行的可怜人的解决方案,您还可以知道 2006 年 1 月 1 日是星期日。

      let weekday = 1 // the day you want text for, 1 == sunday
      var comps = NSDateComponents()
      comps.year = 2006
      comps.day = weekday
      let calendar = NSCalendar(identifier: NSGregorianCalendar)
      let d = calendar?.dateFromComponents(comps)
      let f = NSDateFormatter()
      f.dateFormat = "eee" // short day style, "Sun", there are more available
      let dayName = f.stringFromDate(d!)
      

      我看不出这种方法有什么好处:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-31
        相关资源
        最近更新 更多