String to Date in Java

后端 未结 4 1669
暖寄归人
暖寄归人 2020-12-12 03:04

HI,

I am converting String to Date format. But it returns wrong dates. for example,

String startDate = \"08-05-2010\"; //  (MM/dd/yyyy)
4条回答
  •  感情败类
    2020-12-12 03:23

    If you want to convert a date string of one format to another format, you can use format() and parse() methods of SimpleDateFormat class

    First you need to parse the string to a date object using parse() method setting the source pattern and then format the date object using format() method setting the target pattern:

    SimpleDateFormat sourceFormat = new SimpleDateFormat("MM-dd-yyyy");
    Date sourceFormatDate = sourceFormat.parse("08-05-2010");
    SimpleDateFormat destFormat = new SimpleDateFormat("dd-MMM-yy");
    String destFormatDateString = destFormat.format(sourceFormatDate);
    System.out.println(destFormatDateString); // 05-Aug-10
    

提交回复
热议问题