Search code examples
androiddatetimetimestampsimpledateformatdate-format

Date format conversion in Java not working


In Java for my Android app, I am trying to display Date & Time in the XML which I get "startDateTime" from API response. Below are the details:

This is what I get from API Response:

"startDateTime": "2021-06-26T13:30:00Z"

In Java activity file, I am doing this:

import java.text.SimpleDateFormat;
import java.util.TimeZone;

TextView tvStartDateTime;

tvStartDateTime = itemView.findViewById(R.id.tvStartDateTime);

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateTime = format.format(match.getStartDateTime());
holder.tvStartDateTime.setText(dateTime);

This is what I do in XML:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tvStartDateTime"
    android:textColor="@color/black"
    android:maxLines="1"
    android:textSize="16sp"
    android:paddingLeft="@dimen/side_padding"
    android:paddingRight="@dimen/side_padding"
    android:paddingTop="@dimen/side_padding"
/>

In the app, when I run with this code, I see blank data.

Can anyone help ? Thanks in advance


Solution

  • Try with the below code it will help you.

      LocalDateTime datetime  = LocalDateTime.ofInstant(Instant.parse(match.getStartDateTime()),TimeZone.getTimeZone("GMT").toZoneId() );
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
      holder.tvStartDateTime.setText(formatter.format(datetime));