使用Swift将当前时间设置为yyyy-MM-dd 00:00:00

时间:2015-08-10 06:47:28

标签: 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”

3 个答案:

答案 0 :(得分:3)

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());

Swift 4

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

答案 1 :(得分:2)

从NSDate实例中删除时间部分的最简单方法是

let startOfDate = NSCalendar.currentCalendar().startOfDayForDate(NSDate())

要根据当前时区使用

获取日期
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let startOfDate = calendar.startOfDayForDate(NSDate())
println(startOfDate)

Swift 4

var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
let startOfDate = calendar.startOfDay(for: Date())
print(startOfDate)

答案 2 :(得分:0)

如果您只关心用户设备上的时区,即您不打算将格式化的日期字符串保存到服务器等,那么您可以使用以下代码:

var formatter: NSDateFormatter = NSDateFormatter()
formatter.dateFormat="yyyy-MM-dd 00:00:00 Z"
formatter.stringFromDate(date)

如果您想将该日期字符串保存到服务器,那么您应该将时区信息添加到格式化程序中:

var formatter: NSDateFormatter = NSDateFormatter()
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
formatter.dateFormat="yyyy-MM-dd 00:00:00 Z"
formatter.stringFromDate(date)

<强>更新

现在我明白了你真正想做的事情,你有一个日期字符串而不是NSDate对象作为输入。

您可以使用以下代码实现所需的输出,保留输入的时区信息

let dateString = "2015-08-12 09:30:41 +0000"
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let timeZone = NSTimeZone(forSecondsFromGMT: 0)

let inputDateFormatter = NSDateFormatter()
inputDateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss Z"
inputDateFormatter.calendar = calendar

if let inputDate = inputDateFormatter.dateFromString(dateString) {
    let outPutDateFormatter = NSDateFormatter()
    outPutDateFormatter.calendar = calendar
    outPutDateFormatter.timeZone = timeZone
    outPutDateFormatter.dateFormat = "yyyy-MM-dd 00:00:00 Z"
    print(outPutDateFormatter.stringFromDate(inputDate))
}