ios - 设置当前时间为yyyy-MM-dd 00 :00:00 using Swift

标签 ios swift datetime nsdate nsdateformatter

我想问一下NSDate,如何设置/格式化当前时间,如“2015-08-12 09:30:41 +0000”到“2015-08-12 00:00: 00 +0000

我已经在使用了:

var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .NoStyle
//result date will be : Aug 12, 2015

但值日期在数据库中存储的并不完全为“2015-08-12 00:00:00 +0000”,而是存储为“2015-08-11 17:00:00 +0000 UTC”

最佳答案

let dateString = "2015-08-12 09:30:41 +0000"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
if let dateFromString = dateFormatter.dateFromString(dateString.componentsSeparatedByString(" ").first ?? "") {
    println(dateFromString)  // "2015-08-12 00:00:00 +0000"
}

swift 4

let dateString = "2019-05-04 09:30:41 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.calendar = Calendar(identifier: .gregorian)
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
if let dateFromString = dateFormatter.date(from: dateString.components(separatedBy: " ").first ?? "") {
    print(dateFromString)  // "2019-05-04 00:00:00 +0000"
}

关于ios - 设置当前时间为yyyy-MM-dd 00 :00:00 using Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49856237/

相关文章:

ios - 从嵌套 NSOperations 调用 cancelAllOperations

swift - 如何将 'nil' 设置为 [String : String] dictionary is valid? 的值

date - 从 PRESTO 中的日期时间截断时间

iphone - 本地通知 : repeat "permanently" with arbitrary alert message and incremental badge

ios - 有没有办法用 outlook 的 URL 方案附加文件?

ios - 下载 PDF,保存到文档目录并加载到 UIWebView

excel - 将长日期文本转换为日期/时间

datetime - 使用 WinRT 设置本地时间戳的格式

ios - Realm -更新对象数组中的所有项目而不是仅附加新项目

swift - 如何在 Swift 中枚举简写字典(或转换字典的所有键类型)?