Reputation: 132
For the code below:
public class DateFormatTest {
@Test
public void shouldTestDateFormat() {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
System.out.println(df.format(new Date()));
df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY);
System.out.println(df.format(new Date()));
}
}
The output is :
2/1/16
01.02.16
How do I get the output bellow instead of the previous:
2/1/2016
01.02.2016
Note: The regional settings for short date are: English(US) , MM/dd/yyyy.
I need the output above when I change the locale not the short date pattern. I don't need to care for all the patterns in the world. The code simulates the change of the locale:
localize(Locale.getDefault());
localize(Locale.GERMANY);
private void localize(Locale locale) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
System.out.println(df.format(new Date()));
}
Upvotes: 1
Views: 683
Reputation: 11621
The following code is not guaranteed to work, but unfortunately it's the only way I know, and it works with Oracle's implementation of Java 7 & 8. If it doesn't work, it will print a 2-digit year instead.
private static void printLocalizedDate(Locale locale) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
if (df instanceof SimpleDateFormat)
df = new SimpleDateFormat(
((SimpleDateFormat) df).toPattern().replace("yy", "yyyy")
);
System.out.println(df.format(new Date()));
}
printLocalizedDate(Locale.getDefault());
printLocalizedDate(Locale.GERMANY);
Upvotes: 1
Reputation: 4430
You could create the format string yourself:
DateFormat df = new SimpleDateFormat("M/d/yyyy");
System.out.println(df.format(new Date()));
df = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(df.format(new Date()));
With those format-strings (M/d/yyyy
and dd.MM.yyyy
) you can define the output by yourself as you wish it to be.
In this case:
d
displays the day-of-month without leading 0dd
displays the day-of-month with leading 0M
and MM
are equivalent to d
& dd
displaying the monthyyyy
displays the year in a 4-digit representationUpvotes: 0
Reputation: 8144
public static void main(String args[]){
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat("M/d/yyyy", Locale.GERMAN);
System.out.println("Current Date: " + ft.format(dNow));
ft = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
System.out.println("Current Date: " + ft.format(dNow));
}
use SimpleDateFormat
output :
Current Date: 2/1/2016
Current Date: 01.02.2016
Upvotes: 1