Swift 将总分钟数转换为;HH:mm";格式

Swift 将总分钟数转换为;HH:mm";格式,swift,Swift,我目前正在以分钟格式保存一些时间戳数据,例如550是上午9:10 有没有办法将其转换为字符串“09:10”?我将使用24小时格式 我在iOS应用程序中使用swift,但如果有非语言特定的逻辑,那也会很有帮助 干杯, Josh问题是550到底代表了什么: 如果它表示以分钟为单位的抽象时间间隔,您可能会将其转换为,然后使用准备小时和分钟的字符串表示形式: let timeInterval = TimeInterval(minutes * 60) let formatter = DateCompone

我目前正在以分钟格式保存一些时间戳数据,例如550是上午9:10

有没有办法将其转换为字符串“09:10”?我将使用24小时格式

我在iOS应用程序中使用swift,但如果有非语言特定的逻辑,那也会很有帮助

干杯,
Josh

问题是550到底代表了什么:

  • 如果它表示以分钟为单位的抽象时间间隔,您可能会将其转换为,然后使用准备小时和分钟的字符串表示形式:

    let timeInterval = TimeInterval(minutes * 60)
    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.hour, .minute]
    formatter.unitsStyle = .positional
    formatter.zeroFormattingBehavior = .pad
    let string = formatter.string(from: timeInterval)
    
  • 这是一个简单的“小时和分钟”表示。如果小时数可能超过24小时,此模式尤其有用(例如,1550分钟是25小时50分钟,或1天、1小时和50分钟,具体取决于您是否将
    .day
    添加到
    允许单位
    中)

  • 但是,如果您的意思是550分钟实际上表示一天中的时间,那么您可以使用日历日期计算并使用字符串表示时间:

    let timeInterval = TimeInterval(minutes * 60)
    let date = Calendar.current.startOfDay(for: Date()).addingTimeInterval(timeInterval)
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "HH:mm"
    let string = formatter.string(from: date)
    
    但是,话虽如此,如果这真的代表上午9:10(不是抽象的时间间隔9小时10分钟),并且您希望在UI中显示它,那么您通常会遵循设备的首选时间格式(上午/下午或24小时时钟):

    不管是哪种方式(强制24小时制还是尊重用户的偏好),您实际上是在显示一天中的某个时间,这意味着虽然一年中的大多数日子都是上午9:10,但如果您在我们推出夏时制的那天这样做,它会显示上午10:10,但是如果那天我们回到那天的标准时间,那就是上午8:10


  • 显然,Objective-C中的语法与Swift中的不同,但基本API是相同的(尽管您显然会使用
    NS
    前缀,例如
    nsdatecomponents-formatter
    和/或
    NSDateFormatter
    ).

    看看。
    让小时=550/60
    让分钟=550%60
    你只需要格式化你的字符串
    字符串(格式:“%02d:%02d”,小时,分钟)
    let timeInterval = TimeInterval(minutes * 60)
    let date = Calendar.current.startOfDay(for: Date()).addingTimeInterval(timeInterval)
    let formatter = DateFormatter()
    formatter.timeStyle = .short
    formatter.dateStyle = .none
    let string = formatter.string(from: date)