将String Date转换为String date不同的格式

Mur*_*ran 12 java date-conversion simpledateformat

我是Java新手.Postgres db包含日期格式yyyy-MM-dd.我需要转换为dd-MM-yyyy.

我试过这个,但显示错误的结果

   public static void main(String[] args) throws ParseException {

    String strDate = "2013-02-21";
      DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
      Date da = (Date)formatter.parse(strDate);
      System.out.println("==Date is ==" + da);
      String strDateTime = formatter.format(da);

      System.out.println("==String date is : " + strDateTime);
}
Run Code Online (Sandbox Code Playgroud)

asi*_*d88 33

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy");
Date date = format1.parse("2013-02-21");
System.out.println(format2.format(date));
Run Code Online (Sandbox Code Playgroud)


Tim*_*der 9

您需要使用两个DateFormat实例.一个包含输入字符串的格式,另一个包含输出字符串的所需格式.

public static void main(String[] args) throws ParseException {

    String strDate = "2013-02-21";

    DateFormat inputFormatter = new SimpleDateFormat("yyyy-MM-dd");
    Date da = (Date)inputFormatter.parse(strDate);
    System.out.println("==Date is ==" + da);

    DateFormat outputFormatter = new SimpleDateFormat("dd-MM-yyyy");
    String strDateTime = outputFormatter.format(da);
    System.out.println("==String date is : " + strDateTime);
}
Run Code Online (Sandbox Code Playgroud)


Zah*_*med 5

参考这些格式Java 日期格式文档

日期时间格式

试试这个代码:

String myDate= "2013-02-21";
DateFormat iFormatter = new SimpleDateFormat("yyyy-MM-dd");
DateFormat oFormatter = new SimpleDateFormat("dd-MM-yyyy");
String strDateTime = oFormatter.format(iFormatter.parse(myDate));
Run Code Online (Sandbox Code Playgroud)