1

I am getting date and time as 2017-01-15T21:30:05Z from an API. I want to change the date to JAN 15,2017 and time to 9:30 pm format.

Here is my code without formatting.

News currentNews = newsList.get(position);
String time=currentNews.getTime();
String[] parts=time.split("T");
parts[1]=parts[1].replace("Z","");

dateView.setText(parts[0]);
timeView.setText(parts[1]); 
Marat
  • 6,142
  • 6
  • 39
  • 67
priyanshu goyal
  • 289
  • 1
  • 2
  • 8
  • Such issues have been a lot.. You can SEE here [link](http://stackoverflow.com/questions/8654990/how-can-i-get-current-date-in-android?rq=1) – ku4irka Feb 21 '17 at 19:26

2 Answers2

1

You need to use SimpleDateFormat and Date object. You will need to create 1 SimpleDateFormat with initial style and 1 with desired style. Then create a Date object and parse received from API date to this object. Then print out it using the second SimpleDateFormat.

Try this code:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMM dd, yyyy h:mm a");

try {
    Date d = sdf.parse("2017-01-15T21:30:05Z");
    System.out.println(d);                     // date in INITIAL format
    System.out.println(sdf2.format(d));        // date in DESIRED format
} catch (ParseException e) {
    e.printStackTrace();
}
Marat
  • 6,142
  • 6
  • 39
  • 67
0

You can use le class SimpleDateFormat to parse your String. Then, you can get a Date from it.

Here is an example if usage : Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

For more details, here is the official documentation : https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Community
  • 1
  • 1
user3246654
  • 117
  • 4