Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we create our own date format in Java?

Tags:

java

I need to format a date(yyyyMMDD) into YYYY-MM-DD. Can I create a date format of the latter ?

like image 578
Pan Avatar asked Dec 04 '22 11:12

Pan


2 Answers

Yes. Use SimpleDateFormat.

like image 80
Nivas Avatar answered Dec 22 '22 17:12

Nivas


    SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyyMMdd");
    SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
    String sourceDateStr = "20101012";
    try {
        Date sourceDate = sourceFormat.parse(sourceDateStr);

        String targetDateStr = targetFormat.format(sourceDate);

        System.out.println(targetDateStr);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Gives the output 2010-01-12

like image 27
Kevin D Avatar answered Dec 22 '22 15:12

Kevin D