简体   繁体   中英

Can't parse datetime from server in android

I am trying to get data from server with timestamp format 2020-04-22 22:50:00 and parse it in my android app like 22.04.2020 22:50 or 22 April 2020 22:50 .

But all what I found is how to convert timestamp like this System.currentTimeMillis() to Date.

API method is sending this type of date:

"started": "2020-04-22 22:50:00",
"ended": "0000-00-00 00:00:00"

Use this method to parse your date:

fun parseDate(serverDate: String): String {
    var sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val date = sdf.parse(serverDate)
    sdf = SimpleDateFormat("d MMMM yyyy HH:mm")
    return sdf.format(date)
}

// This would print "22 April 2020 22:50"
print(parseDate("2020-04-22 22:50:00"))

In java it will be:

String server_date = "2020-04-22 22:50:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
    Date date = sdf.parse(trip_date);
    sdf = new SimpleDateFormat("d MMMM yyyy HH:mm");
    textView.setText(sdf.format(date));
} catch (ParseException e) {
    e.printStackTrace();
}

Result: 22 April 2020 22:50

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