Format Timestamp for string without milliseconds?

Asked

Viewed 828 times

0

I have the following variable public Timestamp CreatedAt; She is placed in a textview in this way:

hora.setText(String.valueOf(notificacao.CreatedAt));

The exit is:

2017-06-29 12:31:21.759

I wish it were:

29/06/2017 12:31

How to do?

2 answers

2


Use SimpleDateFormat:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
try {
    Date date = formatter.parse(notificacao.CreatedAt);
    String data = new SimpleDateFormat("dd/MM/yyyy HH:mm").format(date);

} catch (ParseException e) {
    e.printStackTrace();
}

1

You will need to create a method that does the conversion, example:

public static String convertDate(String mDate){

   SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
   try {
          Date newDate = inputFormat.parse(mDate);
          inputFormat = new SimpleDateFormat("dd/MM/yyyy");
          mDate = inputFormat.format(newDate);
    } catch (ParseException e) {
          e.printStackTrace();
    }

   return mDate;
}

Thus, when setting Textview do the following:

hora.setText(convertDate(notificacao.CreatedAt));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.