java - Format String into Date considering localization in GWT -
i have problem cannot format string, having in form of "270317" (german version), date.
for accomplishing this, use gwt. have far this:
string input = "270317"; localeinfo locale = null; if (locale == null) { locale = localeinfo.getcurrentlocale(); } date = datetimeformat.getformat(input).parse(input); the outcome current date: 07/28/2017
what want achieve have date written in country program being executed. if not possible prefer have written in way: 03/27/2017.
to parse input 270317 date, must provide expected format (you're using input format, wrong):
string input = "270317"; date date = datetimeformat.getformat("ddmmyy").parse(input); this parse date correctly, if input format day-month-year. if inputs produced in localized format, can use datetimeformat.getformat(predefinedformat.date_short) or other format - locale-specific , can vary lot between different environments.
check inputs know if you'll need use fixed or localized format.
after parsed date, can format whatever format want. if want locale-specific format, use:
datetimeformat.getformat(predefinedformat.date_short).format(date); this locale specific, output can vary. in system, i've got:
2017-03-27
java new date/time api
although you're using gwt, specific code date parsing/formatting handled better api. gwt uses java.util.date, has lots of problems , design issues.
if you're using java 8, consider using new java.time api. it's easier, less bugged , less error-prone old apis.
if you're using java <= 7, can use threeten backport, great backport java 8's new date/time classes. , android, there's threetenabp (more on how use here).
the code below works both. difference package names (in java 8 java.time , in threeten backport (or android's threetenabp) org.threeten.bp), classes , methods names same.
to parse , format date, can use datetimeformatter. you're using day, month , year, i'm using localdate class (which has date fields):
string input = "270317"; // parse date datetimeformatter parser = datetimeformatter.ofpattern("ddmmyy"); localdate date = localdate.parse(input, parser); // locale specific format datetimeformatter formatter = datetimeformatter.oflocalizeddate(formatstyle.short); system.out.println(formatter.format(date)); as locale specific, in system i've got output:
27/03/17
if want use same pattern produced gwt, can use:
// gwt format string pattern = datetimeformat.getformat(predefinedformat.date_short).getpattern(); // use same format in formatter datetimeformatter formatter = datetimeformatter.ofpattern(pattern); system.out.println(formatter.format(date)); based on gwt docs, seems use patterns compatible datetimeformatter (at least date fields), should work cases.
if want fixed format (like 03/27/2017), do:
datetimeformatter formatter = datetimeformatter.ofpattern("dd/mm/yyyy"); check javadoc more details date patterns.
Comments
Post a Comment