Reputation: 364
How to convert DateTime to Local Date Format?
Example: date: 1/25/2014 12:00:00 AM This date is US format but in my machine I use TR format 25/1/2014 and also assume that another machine use another format Example: 2014/1/25
How can I convert this date to local date format programmaticaly?
I am using java version 1.7 and i want to use java.util.Calendar
Thanks in advance.
Upvotes: 0
Views: 514
Reputation: 79075
DateTimeFormatter.ofLocalizedDateTime
Use it to obtain a locale-specific date format for the ISO chronology.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfLocalized = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT);
// Test
LocalDateTime date = LocalDateTime.now();
System.out.println(dtfLocalized.withLocale(Locale.US).format(date));
System.out.println(dtfLocalized.withLocale(Locale.UK).format(date));
System.out.println(dtfLocalized.withLocale(Locale.CHINESE).format(date));
System.out.println(dtfLocalized.withLocale(Locale.GERMAN).format(date));
System.out.println(dtfLocalized.withLocale(Locale.forLanguageTag("tr")).format(date));
System.out.println(dtfLocalized.withLocale(Locale.getDefault()).format(date));
}
}
Output:
5/8/21, 6:54 PM
08/05/2021, 18:54
2021/5/8 下午6:54
08.05.21, 18:54
8.05.2021 18:54
08/05/2021, 18:54
Note: If you want to format just the date part, replace DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT)
with DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Upvotes: 3