将DateTime转换为String

时间:2018-10-26 13:16:44

标签: android datetime type-conversion

如果您能帮助我实现从DateTime格式(08/30/2018)到这种类型的字符串“ August 30,2018”的转换,我将不胜感激。我正在进行刷新,我想在TextView上显示类似的内容。 谢谢

4 个答案:

答案 0 :(得分:1)

使用此代码进行转换:

SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.getDefault());
SimpleDateFormat outputFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.getDefault());
Date date;
String result = "";
try {
    date = inputFormat.parse("set your input date here");
    result = outputFormat.format(date); // here will be output date
} catch (e: ParseException) {
    Log.e("Error", "Parse exception", e);
}

答案 1 :(得分:0)

尝试

 String date ="2017-05-05 13:58:50 ";
            SimpleDateFormat input = new SimpleDateFormat("MM/dd/yyyy");
            SimpleDateFormat output = new SimpleDateFormat("MMMM dd,yyyy");
            try {
                 Date oneWayTripDate = input.parse(date);  // parse input
            } catch (ParseException e) {
                e.printStackTrace();
           }

答案 2 :(得分:0)

String d = "08/30/2018";
LocalDate date = LocalDate.parse(d, DateTimeFormatter.ofPattern("MM/dd/yyyy"));
String newDate = date.format(DateTimeFormatter.ofPattern("MMMM dd, yyyy"));
System.out.println(newDate);

将打印

August 30, 2018

编辑(如果要考虑较低的api),可以执行以下操作:

String d = "08/30/2018";
String newDate = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    LocalDate date = LocalDate.parse(d, DateTimeFormatter.ofPattern("MM/dd/yyyy"));
    newDate = date.format(DateTimeFormatter.ofPattern("MMMM dd, yyyy"));
} else {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    Date date = null;
    try {
        date = sdf.parse(d);
        sdf = new SimpleDateFormat("MMMM dd, yyyy");
        newDate = sdf.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

答案 3 :(得分:0)

使用此示例:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd/MM/yyyy"); Date now = new Date(); String time = sdf.format(now);