swift - 无法获取正确的时间 :minutes string from NSDate() in Swift

标签 swift nsdate nsdateformatter

总是打印 11:04 ,关于此代码返回当前时间(以小时:分钟为单位)有什么问题吗?

import UIKit

extension NSDate {

    func currentTimeInHoursAndMinutes() -> String {

        let dateFormatter = NSDateFormatter()
        dateFormatter.locale = NSLocale.currentLocale()
        dateFormatter.timeZone =  NSTimeZone.localTimeZone()
        dateFormatter.dateFormat = "HH:MM"
        let timeStr = dateFormatter.stringFromDate(self)
        print("timeStr:\(timeStr) for nsdate:\(self)")
        return timeStr
    }
}

let time = NSDate().currentTimeInHoursAndMinutes()

最佳答案

您使用的是月份而不是分钟,如果您继续使用月份,则在这一小时的剩余时间内,时间看起来会是相同的。

dateFormatter.dateFormat = "HH:mm"

Unicode Date Format Patterns

关于swift - 无法获取正确的时间 :minutes string from NSDate() in Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36631267/

相关文章:

ios - 在 Swift 中使用 NSDate 组件

iphone - UIDatePicker,根据日期名称和今天的日期设置最大和最小日期

ios - Objective-C - 获取本地化的周末和工作日名称?

swift - 使用 SearchBar 时,复选标记与 TableView 中的错误行相关联

iOS prepareforsegue 抛出 xc_bad

ios - 委托(delegate)函数未被调用 iOS Swift

iphone - 如何创建一个完整的 NSDate 对象来表示下一个指定的日期时间?

ios - Objective-C 日期格式化程序。 yyyy-MM-dd hh :mm:ss change to yyyy-MM-dd

iOS7如何根据指定时区获取当前时间和日期?

ios - 如何从 UITableView 中的数组中获取用户选择的值并将该值传递给服务器