问题
I am develop in Android
The day of String is 2020-04-23T23:59:59-04:00
And try to use the following function to convert the time to 2020-04-23
fun changeDateFormat(strDate:String):String {
return SimpleDateFormat("yyyy-MM-dd").format(SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ").parse(strDate))
}
But it show 2020-04-24
Did I missing something ? Thanks in advance.
回答1:
here is how you can achieve it
val dateInString = "2020-04-23T23:59:59-0400"
val ldt: LocalDateTime = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"))
val currentZoneId: ZoneId = ZoneId.systemDefault()
val currentZonedDateTime: ZonedDateTime = ldt.atZone(currentZoneId)
val format: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val formattedDate = format.format(currentZonedDateTime)
println(formattedDate)
回答2:
You should use DateTimeFormatter and LocalDate from java.time.
for example
val timestampAsDateString = "2020-04-23T23:59:59-04:00"
val format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZZZZZ")
val date = LocalDate.parse(timestampAsDateString, format)
Log.d("parseTesting","Date : ${date}") // logs 2020-04-23
since LocalDate is a date without time-zone in the ISO-8601 calendar system the output is already in yyyy-MM-dd format.
回答3:
Your time must not contain colon in between(-04:00)
This worked out well for me and returned the desired result
fun changeDateFormat(strDate:String):String {
val sourceSdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault())
val requiredSdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
return requiredSdf.format(sourceSdf.parse(strDate))
}
来源:https://stackoverflow.com/questions/61379415/how-to-convert-yyyy-mm-ddthhmmsszzzzz-to-yyyy-mm-dd-without-add-one-day