-1

i want to convert this 01/20/2021 20:10:14 to this format yyyy-MM-dd'T'HH:mm:ss.SSS'Z' in android. currently i am using function but when i convert to local format i don't get original time

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
    }
Sagar
  • 585
  • 1
  • 9
  • 28

1 Answers1

1

You should use the modern java.time API for dates, times, etc.

Firstly we need to format the input string. As mentioned in the comment in the question, the zone information is required to correctly format the input date string.

This gives us a TemporalAccessor object. Now, we need to convert this object to an object of the Instant class. An Instant object is always treated to be at 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()
}
Xid
  • 4,578
  • 2
  • 13
  • 35
  • that's correct, but the formatter pattern should be "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" according to the question ;) – Nicola Gallazzi Jan 21 '21 at 17:28
  • The pattern here is that of the input string. The 'Z' in output string symbolizes UTC time. That is being done through the `Instant` object – Xid Jan 21 '21 at 17:32
  • @KyzerSoze i know that class but this class is supported from API level 26 and my minsdk is 21 so i can not use this class – Sagar Jan 22 '21 at 07:28
  • If possible, you can use [desugaring](https://stackoverflow.com/a/61218004/12313157) – Xid Jan 22 '21 at 11:18