swift 毫秒或秒 转 时间 (日时分秒)

调用时直接传入秒数即可;需要注意的参数属性为 : .pad 和 .positional;根据自己的需求变动;

、、、

//  second 秒数
 func FormatDate(second:Int) ->String{

   let formatter = DateComponentsFormatter.init()
    // . dropMiddle为  0d 00h 00m 格式 (需要其它格式可以自己点进去看看)
    formatter.zeroFormattingBehavior = .dropMiddle

  // 此处事例只写了 日 时 分;需要秒的可以在后面加上(参数: | NSCalendar.Unit.second.rawValue )
    formatter.allowedUnits = NSCalendar.Unit(rawValue: NSCalendar.Unit.day.rawValue | NSCalendar.Unit.hour.rawValue | NSCalendar.Unit.minute.rawValue)

    formatter.unitsStyle = DateComponentsFormatter.UnitsStyle.abbreviated
    
  // 结果默认格式为 1d 1h 1m
    var resultStr = formatter.string(from: TimeInterval(seconds)) ?? ""

  // 处理为 1天 1小时 1分钟 (根据自己需求处理)
    resultStr = resultStr.replacingOccurrences(of: "d", with: "天", options: .literal, range: nil)
    resultStr = resultStr.replacingOccurrences(of: "h", with: "小时", options: .literal, range: nil)
    resultStr = resultStr.replacingOccurrences(of: "m", with: "分钟", options: .literal, range: nil)
    
    return resultStr

}

、、、

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容