本文将说明在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 **/