I'm trying to change the date format I get through an API request. I use GsonBuilser. As I understand it, when changing parameters in setDateFormat (""), the format should change. But with any changes, it gives the result: 2008-01-12T07: 51: 46Z

How do I get a normal date display? Maybe even just dates, without time? Thank! Code below

Gson gsonDate = new GsonBuilder() //.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .setDateFormat(DateFormat.SHORT, DateFormat.SHORT) .create(); Retrofit retrofitDate = new Retrofit.Builder().baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(gsonDate)).build(); GitHubUser gitHubUserDate = retrofitDate.create(GitHubUser.class); Call<PojoGitUser> callDate = gitHubUserDate.getUserInfo(login); callDate.enqueue(new Callback<PojoGitUser>() { @Override public void onResponse(Call<PojoGitUser> call, Response<PojoGitUser> response) { PojoGitUser infoDate = response.body(); tvDate.setText("Bio: " + infoDate.getCreatedAt()); } @Override public void onFailure(Call<PojoGitUser> call, Throwable t) { } }); } public interface GitHubUser { @GET("users/{username}") Call<PojoGitUser> getUserInfo(@Path("username") String login); } 
  • What type do you get with the infoDate.getCreatedAt() method? Setting setDateFormat affects the conversion of fields of type java.util.Date, java.sql.Timestamp and java.sql.Date to json and back, but not to display them on the screen. - woesss
  • It looks like a string. public String getCreatedAt () {return createdAt; } I do not understand what to do about it. How can I change the type? - Kate Sh

1 answer 1

The date that comes from the "2018-10-27T06:34:39+00:00"

Like this:

 private String getFormattedDate(String rawDate) { SimpleDateFormat utcFormat = new SimpleDateFormat(RESPONSE_FORMAT, Locale.ROOT); SimpleDateFormat displayedFormat = new SimpleDateFormat(MY_FORMAT, Locale.getDefault()); try { Date date = utcFormat.parse(rawDate); return displayedFormat.format(date); } catch (ParseException e) { throw new RuntimeException(e); } } 

And I request in the adapter:

 String my_date = getFormattedDate(newsPojoList.get(position).getPublishedAt()); 

where getPublishedAt() getter that returns a date from JSON : "2018-10-27T06:34:39+00:00"