Can we create our own date format in Java?

I need to format the date (yyyyMMDD) to YYYY-MM-DD. Can I create a date format for the last?

+4
source share
4 answers
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 a conclusion 2010-01-12

+7
source

Yes. Use SimpleDateFormat .

+10
source

To do this, you can use a pre-written class, for example pojava http://www.pojava.org/ . It is very good to recognize different date formats and translate between them.

For example, to translate between the formats above:

 try { System.out.println("Date:" + new DateTime("Date").toString("yyyy-MM-dd")); } catch (Exception error) { error.printStackTrace(); } 

I find that using this class helps, since I don’t have to worry too much about the different date formats that exist there (except for the UK / USA dd / MM / yyyy and MM / dd / yyyy, which you can customize the class for)

0
source

Take a look at joda-time: http://joda-time.sourceforge.net/

0
source

All Articles