使用Swift将当前时间设置为yyyy-MM-dd 00:00:00 [英] Set current time to yyyy-MM-dd 00:00:00 using Swift

查看:303
本文介绍了使用Swift将当前时间设置为yyyy-MM-dd 00:00:00的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to ask about NSDate, how to set/format current time like "2015-08-12 09:30:41 +0000" to "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

but the value date is not stored in the Database exactly as "2015-08-12 00:00:00 +0000" but storing as "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



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"
}

这篇关于使用Swift将当前时间设置为yyyy-MM-dd 00:00:00的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆