Set current time to yyyy-MM-dd 00:00:00 using Swift

后端 未结 3 823
广开言路
广开言路 2021-01-25 02:25

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

I\'m already using :

         


        
3条回答
  •  北荒
    北荒 (楼主)
    2021-01-25 02:58

    If you only care about the timezone on user's device, i.e, you are not going to save that formatted date string to server, etc, then, you can use the following code:

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

    If you want to save that date string to server as well, then, you should add timezone info to the formatter:

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

    Update

    Now I understand what you actually wanted to do, you have a date string instead of a NSDate object as an input.

    You can use the following code for achieving your desired output, with respect to preserving timezone info of the input.

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

提交回复
热议问题