【问题标题】:Swift 3 - Formatting Time String from String.CharacterView formatted stringSwift 3 - 从 String.CharacterView 格式化字符串格式化时间字符串
【发布时间】:2017-05-22 00:10:18
【问题描述】:

我试图弄清楚如何格式化已经使用 String.CharacterView 格式化的字符串。

代码是:

let formattedDate = arrivalTime.characters.suffix(8) //gets the last 8 characters of a JSON outputted string for the time
 record.time = String(formattedDate) //sets the characters to a string and then sets that equal to the record class variable time, which displays the string in each table view cell
 self.records.append(record)

这会产生类似

的字符串
18:41:21

我想弄清楚的是如何获得像

这样的字符串
6:41pm 

而不是 18:41:21

有人有什么建议吗?谢谢!

【问题讨论】:

    标签: ios json swift string swift3


    【解决方案1】:

    您可以使用 components(separatedBy: ":") 解析字符串并将元素映射为整数。然后,您可以使用第一个组件(小时)截断除以 12 的余数来格式化结果字符串,并根据其值有条件地添加 ampm

    let time24h = "18:41:21"
    let components = time24h.components(separatedBy: ":").flatMap{Int($0)}
    if components.count > 1 {
        let time12h =  String(format: "%d:%02d", components[0] % 12, components[1])
            + (components[0] < 12 ? "am" : "pm")  //  "6:41pm"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      相关资源
      最近更新 更多