简体   繁体   中英

Java convert timestamp object to date format

In my Android app, I'm showing an List<Object> , it contains String , int and Timestamp values, and I don't know which item is the Timestamp one.
Now it appears like this: Timestamp(seconds=1556208432, nanoseconds=754000000)

What I wanna do is parse this into a readable Date format.
Here's the code I tried:

TextView t2 = view.findViewById(android.R.id.text2);
String tS2 = String.valueOf(values.get(position));

if(tS2.contains("Timestamp(seconds=")) {
    long ts = Timestamp.parse(tS2);
    Date date = new Date(ts);
    Log.d(TAG, "date: "+date);
} else {
    t2.setText(tS2);
}

And parse it with SimpleDateFormat, like this:

String myFormat = "yyyy MMM dd";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.ENGLISH);
t2.setText(sdf.format(something));

I get this error:

java.lang.IllegalArgumentException at java.util.Date.parse

EDIT1:

It dies with the error below when it gets to the Date part.

Object time = values.get(position);
com.google.firebase.Timestamp ts = (com.google.firebase.Timestamp) time;
String str = ts.toString();
Date date = new Date(Long.parseLong(str));

java.lang.NumberFormatException: For input string: "Timestamp(seconds=1556208432, nanoseconds=754000000)"

You are converting the timestamp to string which will not convert the value it's holding to string but describe the object itself .

To get the date of the Firebase timestamp just call toDate() on it.

For more info check this out

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM