2017-05-30 58 views
0

我想解析字符串到日期但得到零的某些特定日期的值。無法解析在iOS中的字符串日期類型swift 3

解析2017-04-21 09:00:00 Tis成功,但獲取字符串2017-05-30 23:00:00的零值。

這裏我的代碼:

func checkingDate(date: String) -> Bool { 

    let dateFormatter = DateFormatter() 
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" 
    dateFormatter.locale = Locale.init(identifier: "en_GB") 

    let dateObj = dateFormatter.date(from: date) 

    dateFormatter.dateFormat = "yyyy-MM-dd" 
    print("Dateobj: \(dateFormatter.string(from: dateObj!))") 
    let now = Date() 

    if let currentData = dateObj { 

     if (currentData >= now) { 
      print("big") 
      return true 
     } else if currentData < now { 
      print("small") 
      return false 
     } 
    } 

    return false 
} 

在此先感謝

+0

你爲什麼要將語言環境設置爲'en_GB'?如果有的話,至少在解析原始字符串時需要使用'en_US_POSIX'。 – rmaddy

回答

1

您使用hh隨着時間的符。這是一個12小時的價值,「23」明顯超出該範圍。 ( 「09」 分析,因爲它是在範圍內。)

使用HH代替:

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" 
+0

謝謝你Jon Skeet –

1

使用大寫字母H代表24小時時間小寫h爲12小時

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" 
0

您需要的dateformater更改爲YYYY-MM-DD HH:MM:SS。 HH用於顯示24小時。

func checkingDate(date: String) -> Bool { 

     let dateFormatter = DateFormatter() 
     dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" 
     dateFormatter.locale = Locale.init(identifier: "en_GB") 

     let dateObj = dateFormatter.date(from: date) 

     dateFormatter.dateFormat = "yyyy-MM-dd" 
     print("Dateobj: \(dateFormatter.string(from: dateObj!))") 
     let now = Date() 

     if let currentData = dateObj { 

      if (currentData >= now) { 
       print("big") 
       return true 
      } else if currentData < now { 
       print("small") 
       return false 
      } 
     } 

     return false 
    }