I am trying to decode the date-time receiving from my APIs in my required format "yyyy-MM-dd"
I receive time in 2 format
1. "2022-05-05T11:32:12.542Z"
2. "2022-05-06T07:33:46.59928 00:00"
I am able to decode first format by parsing it using following pattern
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
but not able to understand the format for the 2nd condition.
Some more example example of 2nd Condition
"2022-05-06T06:30:25.583988 00:00"
"2022-05-05T11:32:49.393283 00:00"
P.S. I don't required parsing logic only needed the pattern
Full method used in the code for parsing 1st Condition
fun convertToFormat(src: String): String {
val originalFormat =
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
val targetFormat = SimpleDateFormat("yyyy-MM-dd")
val date = originalFormat.parse(src)
return targetFormat.format(date)
}
CodePudding user response:
tl;dr
If you only want to just pull the date portion of the input string, split.
"2022-05-05T11:32:12.542Z"
.split( "T" )
[ 0 ]
If you want to parse the input string, use OffsetDateTime
& LocalDate
.
OffsetDateTime
.parse(
input
)
.toLocalDate()
.toString() ;
Avoid legacy classes
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined by JSR 310. Never use SimpleDateFormat
, Date
, Calendar
.
ISO 8601
Both of your exemple strings represent a moment as seen with an offset from UTC of zero hours-minutes-seconds.
Both of your example strings are in standard ISO 8601 format. The java.time classes support ISO 8601 formats by default when parsing/generating text. So no need to specify a formatting pattern.
Instant
Parse your input as objects of class Instant
.
Instant instant1 = Instant.parse( "2022-05-05T11:32:12.542Z" ) ;
Instant instant2 = Instant.parse( "2022-05-06T07:33:46.59928 00:00" ) ;
See this code run live at IdeOne.com.
LocalDate
You want date only. So convert to the more flexible OffsetDateTime
, and extract LocalDate
.
LocalDate ld = Instant.atOffset( ZoneOffset.UTC ).toLocalDate() ;
Then call LocalDate#toString
to generate text in ISO 8601 format YYYY-MM-DD.
Android
The java.time classes are built into Java 8 and later.
Android 26 carries an implementation of java.time. For earlier Android, the latest tooling provides most of the functionality via “API desugaring”.
CodePudding user response:
I was looking the SimpleDateFormat Docs, and found this reference: https://developer.android.com/reference/kotlin/java/text/SimpleDateFormat#examples
The pattern "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
, looks like very similar with this you are receiving (except about the seconds precision).