如何将 "year-month-day" 日期格式(例如:2015-05-12-这是从服务器检索到的值)转换为 android 中的 "day-month-year" 格式

How to convert "year-month-day" date format(eg: 2015-05-12-which is a value retrieved from server) to "day-month-year" format in android

如何将 "year-month-day" 日期格式(例如:2015-05-12-这是从服务器检索到的值)转换为 android 中的 "day-month-year" 格式。

我从服务器获得的实际值是年-月-月格式。但是我需要在 app.How 中将它显示为 day-mnth-yr 我可以实现吗?

首先,您需要将字符串解析为日期。然后根据需要格式化日期,下面的示例是 BalusC 对该主题的回答的编辑版本:Change date format in a Java string

String oldstring = "2015-05-12";
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(oldstring);
//Use SimpleDateFormat#format() to format a Date into a String in a certain pattern.

String newstring = new SimpleDateFormat("dd-MM-yyyy").format(date);
System.out.println(newstring); // 12-05-2015

如果你这样说,我想你的意思是在一个字符串中,所以你可以使用

将字符串转换为日期
String dateServer = "2015-05-12";
//Identify the format which has been used from server
DateFormat format = new SimpleDateFormat("yyyy, MM, dd", Locale.ENGLISH);
//Convert string to Date using this format
Date date = format.parse(string);
//Create the format you need to print
DateFormat wellFormatted = new SimpleDateFormat("dd/MM/yyyy");
//now convert the date into a string formatted as you like
String wellPrintedDate = wellFormatted.format(date);

就这些,"wellPrintedDate"就是day/month/yeah格式的字符串。 here 您可以找到用于格式化的代码列表:)

try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date past = format.parse("2015-05-12");
        SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy");
        System.out.println("dt=" + format1.format(past));
    } catch (ParseException e) {
        e.printStackTrace();
    }
  public static String formattedDateFromString(String inputFormat, String outputFormat, String inputDate){
    if(inputFormat.equals("")){ // if inputFormat = "", set a default input format.
        inputFormat = "yyyy-MM-dd";
    }
    if(outputFormat.equals("")){
        outputFormat = "dd-mm-yyyy"; // if inputFormat = "", set a default output format.
    }
    Date parsed = null;
    String outputDate = "";

    SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault());
    SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault());

    // You can set a different Locale, This example set a locale of Country Mexico.
    //SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, new Locale("es", "MX"));
    //SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, new Locale("es", "MX"));

    try {
        parsed = df_input.parse(inputDate);
        outputDate = df_output.format(parsed);
    } catch (Exception e) {
        Log.e("formattedDateFromString", "Exception in formateDateFromstring(): " + e.getMessage());
    }
    return outputDate;

}

像这样打电话

  Log.e("",""+formattedDateFromString("yyyy-MM-dd","dd-MM-yyyy","2015-05-12"));


output:  12-05-2015