如何将以下时间戳格式化为Android中的可读字符串?

时间:2017-04-25 19:39:11

标签: android timestamp

我的应用从具有以下时间戳结构的网站中提取文章:

  

2017-04-25T00:00:00-05:00

如何将其转换为可读取的格式:

April 25, 2017 12:00 AM

感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用时间戳格式化字符串,例如:

SimpleDateFormat smDateFormat = new SimpleDateFormat("MMMM d, yyyy hh:mm");
String dateString = smDateFormat.format([timestamp]);

修改

我试着这样做......

Timestamp timestamp = new Timestamp(System.currentTimeMillis());

SimpleDateFormat smDateFormat = new SimpleDateFormat("MMMM dd, yyyy - HH:mm", Locale.US);
String dateString = smDateFormat.format(timestamp);

Toast.makeText(this, dateString, Toast.LENGTH_LONG).show();

...输出为:

Example output

答案 1 :(得分:0)

我确信有一种更简单的方法可以做到这一点,但这是我创建的解决方案:

public static String convertADevotionTimestamp(String time){
        String year = time.substring(0,4);
        String month = time.substring(5,7);
        String date = time.substring(8,10);
        String hour = time.substring(11,13);
        String minute = time.substring(14,16);

        // Format month
        int monthNum = Integer.parseInt(month);
        String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
        month = months[monthNum - 1];

        // Format AM vs PM
        String amOrPm = null;
        int hourNum = Integer.parseInt(hour);
        if (hourNum >= 12){
            amOrPm = "pm";
            hour = String.valueOf(hourNum - 12);
        } else {
            amOrPm = "am";
            if (hourNum == 0){
                hour = "12";
            }
        }

        return month + " " + date + ", " + year + " at " + hour + ":" + minute + amOrPm + " ET";
    }