Tuesday, 15 April 2014

java - Convert mediumDate() to other format (with Locale) on Joda-Time -



java - Convert mediumDate() to other format (with Locale) on Joda-Time -

i've problem convert date in other format in java (i'm using joda-time). in fact, i've formatted local date is:

24/giu/14 (italian format date...but other local formats possible)

i see in output (using locale format date):

24/06/2014

i tried build sample code, doesn't works...what doing wrong?

public string dateconvertfrommediumformattoslash (string date) { datetimeformatter dtf = datetimeformat.mediumdate().withlocale(locale.getdefault()); localdate dt = dtf.parselocaldate(date); homecoming dt.tostring(); // output: 2014-06-24 }

your question confusing regards have input , want output.

italy uses hyphens, not slashes

but 1 problem seems slashes. joda-time expects hyphens not slashes. here illustration code using joda-time 2.3 showing localdate looks string using medium format locale of italy.

localdate localdate = new localdate( 2014, 6, 24 ); system.out.println( "localdate: " + localdate ); datetimeformatter formatter = datetimeformat.mediumdate().withlocale( locale.italy ); system.out.println( "output: " + formatter.print( localdate ) );

when run…

class="lang-none prettyprint-override">localdate: 2014-06-24 output: 24-giu-2014 define formatter slashes

so if want parse/generate string slashes instead of hyphens expected locale of italy, must explicitly define such formatter.

string input = "24/giu/14"; datetimeformatter formatterinput = datetimeformat.forpattern( "dd/mmm/yy").withlocale( locale.italy ); localdate localdate = formatterinput.parselocaldate( input ); system.out.println( "localdate: " + localdate ); datetimeformatter formatteroutput = datetimeformat.forpattern( "dd/mm/yy").withlocale( locale.italy ); // locale not needed here, it's habit specify. string output = formatteroutput.print( localdate ); system.out.println( "output: " + output );

when run…

class="lang-none prettyprint-override">localdate: 2014-06-24 output: 24/06/14

by way, using 2 digits year asking problem imho.

java date datetime converter jodatime

No comments:

Post a Comment