将本地日期时间转换为UTC格式



我想将01/20/2021 20:10:14转换为yyyy-MM-dd 'HH:mm:ss。android中的SSS' z '。目前我正在使用函数,但当我转换为本地格式时,我没有得到原始时间

fun convertDate (date : String) : String {
var convertedDate = ""
val calendar = Calendar.getInstance()
val timeformat = SimpleDateFormat("HH:mm:ss")
val time = timeformat.format(calendar.time)
val formatter = SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
val odate = formatter.parse(date+" "+time)
val utcformat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
convertedDate = utcformat.format(odate)
return convertedDate
}

您应该使用现代java.timeAPI来获取日期、时间等。

首先,我们需要格式化输入字符串。正如在问题的注释中提到的,要正确格式化输入的日期字符串,需要使用区域信息。

这给我们一个TemporalAccessor对象。现在,我们需要将这个对象转换为Instant类的对象。Instant对象总是被视为UTC。

fun convertDate (date : String) : String {
val formatter = DateTimeFormatter
.ofPattern("MM/dd/yyyy HH:mm:ss")
.withZone(ZoneId.systemDefault())
val instant = Instant.from(formatter.format(date))
return instant.toString()
}

最新更新