2017-10-05 55 views
0

爲什麼?我將字符串轉換爲日期,輸入不同的輸出?將字符串轉換爲日期不同於swift 3

Input: 
let formatter = DateFormatter() 
formatter.dateFormat = "yyyy-MM-dd" 
dateLahir = formatter.date(from: "2017-10-05") 
print("date: \(dateLahir)") 

Output: 
date: 2017-10-04 
+1

顯示打印的'實際完成輸出(「日期:\( dateLahir)「)'。 – rmaddy

+1

順便說一句 - 你的代碼很好。你只需要瞭解打印一個Date對象的輸出。 – rmaddy

+2

日期格式化程序將使用您當前的時區轉換日期字符串,而'print'通常會以GMT格式顯示相應的日期/時間(最後您會看到一個「+ 0000」,這就是rmaddy要求共享的原因來自'print'語句的完整字符串)。底線,不要擔心什麼時間'印刷'恰好使用。轉換爲「日期」對象或從「日期」對象轉換時,始終使用日期格式化程序(例如,如果在應用程序中顯示日期,請使用DateFormatter構建字符串以顯示最終用戶)。 – Rob

回答

0

在斯威夫特3 轉換日期爲字符串

class func convertDateToString(_ dateStr:String?, fromDateFormat currentFormat:String, toDateFormat newFormat:String) -> String? 
    { 
     if dateStr == nil 
     { 
      return nil; 
     } 

     let formatter:DateFormatter = DateFormatter(); 
     formatter.dateFormat = currentFormat; 
     let date = formatter.date(from: dateStr!); 
     if date == nil 
     { 
      return ""; 
     } 
     formatter.dateFormat = newFormat; 
     let newStr : String = formatter.string(from: date!); 
     return newStr; 
    } 

字符串轉換爲日期

class func convertStringToDate(_ strDate:String, dateFormat:String) -> Date? 
{ 
    let formatter:DateFormatter = DateFormatter(); 
    formatter.dateFormat = dateFormat; 
    formatter.timeZone = TimeZone.autoupdatingCurrent 
    let date = formatter.date(from: strDate); 
    return date; 
}