2017-05-30 60 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 
    }