java.time
You are using old date-time classes that have proven to be poorly designed, confusing, and troublesome. They have been supplanted by the java.time classes built into Java 8 and later. Defined by JSR 310. Much of that functionality has been back-ported to Java 6 & 7 in the ThreeTen-Backport project and further adapted to Android in the ThreeTenABP project.
If you have a java.util.Date object, convert it to an Instant
object, a moment on the timeline in UTC with a resolution of nanoseconds. New methods have been added to the old classes to facilitate conversion.
Instant instant = myJavaUtilDate.toInstant();
Or get the current moment. In Java 8, the current moment is captured only with millisecond resolution, despite the Instant
class’ capacity for nanoseconds. In Java 9, the current moment is captured with up to nanosecond resolution (depending on your computer hardware clock capability).
Instant instant = Instant.now();
Apply a time zone for the locality whose wall-clock time you want to see. This is important even for a date-only value as the date varies around the world at any given moment. A new day dawns earlier in the east.
I choose a New Zealand time zone arbitrarily, for demonstration. Apply a ZoneId
to get a ZonedDateTime
object.
Use proper time zone names, never the 3-4 letter codes you see in the media such as IST
or EST
. Such codes are not standardized nor even unique.
ZoneId zoneId = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
The time zone has nothing to do with localization into a human language such as Malay. A Locale
handles that, as well as defining cultural norms to use for issues such as ordering of the elements or using period vs comma.
My example assumes you were correct in specifying the language and country/culture codes.
Locale locale = new Locale( "ms" , "MY" );
The java.time.format package has classes that can automatically localize when generating a String to represent a java.time value.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM );
When defining a formatter, remember to specify the Locale
. If omitted, your JVM’s current default Locale will be applied implicitly. That default can change at any moment, even during runtime! So better to be always be explicit.
formatter = formatter.withLocale( locale );
String output = zdt.format( formatter );
23 Mei 2016
By comparison when using Locale.US
:
May 23, 2016
And when using Locale.CANADA_FRENCH
:
2016-05-23