本文將說明在Android應用程序中將日期/時間從一個時區轉換為另一個時區的概念。
在整個過程中,我們需要將日期對象轉為字符串或者將字符串轉為日期對象。要在Android中進行轉換,我們使用SimpleDateFormat類,如下所示:
/** Converting from String to Date **/
fun String.getDateWithServerTimeStamp(): Date? {
val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
Locale.getDefault())
dateFormat.timeZone = TimeZone.getTimeZone("GMT") // IMP !!!
try {
return dateFormat.parse(this)
} catch (e: ParseException) {
return null
}
/** Converting from Date to String**/
fun Date.getStringTimeStampWithDate(): String {
val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
Locale.getDefault())
dateFormat.timeZone = TimeZone.getTimeZone("GMT")
return dateFormat.format(this)
}
/** TESTING **/
val dateString = "2018-01-09T07:06:41.747Z"
val date = dateString.getDateWithServerTimeStamp()
Log.d("LOG", "String To Date Conversion " +date.toString())
val dateBackToString = date?.getStringTimeStampWithDate()
Log.d("LOG", "Date To String Conversion " +dateBackToString)
/** OUTPUT **/
String To Date Conversion Tue Jan 09 15:06:41 GMT+08:00 2018
Date To String Conversion 2018-01-09T07:06:41.747Z
/** NOTE: I am currently at GMT+08:00 **/