Reputation: 132
Is it possible to localize Java calendar class to convert current system date to for example Jalali (Persian) date?
Upvotes: 0
Views: 1018
Reputation: 338326
How to localize Java Calendar class?
You don’t. Instead, you localize a ZonedDateTime
object.
The terrible Calendar
class, actually GregorianCalendar
, was supplanted years by the ZonedDateTime
class. All the awful old date-time classes from the earliest versions of Java (Date
, Calendar
, SimpleDateFormat
, java.sql.Timestamp
, java.sql.Date
, etc.) were all outmoded by the modern java.time classes.
You can easily convert from the legacy classes to the modern by calling new methods added to the old classes.
ZonedDateTime zdt = ( ( GregorianCalendar ) myCalendar ).toZonedDateTime() ;
Now let DateTimeFormatter
automatically localize while generating a String
representing textually the date-time value.
To localize, specify:
FormatStyle
to determine how long or abbreviated should the string be.Locale
to determine:
Example:
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( l ) ;
String output = zdt.format( f ) ;
convert current system date to for example Jalali (Persian) date?
Java does come bundled with an implementation of Chronology
for the Hijrah calendar system: HijrahChronology
. Perhaps that might meet your needs (I know next-to-nothing about chronologies other than ISO 8601).
You might learn more about this by searching Stack Overflow.
If that implementation does not meet your needs, you might find one elsewhere or develop your own. Besides the several open-source chronologies bundled with Java, you will find several more in the ThreeTen-Extra project, all open-source. You might find others from other sources.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Upvotes: 1
Reputation: 240870
When you create instance you pass the Locale
, for example
Calendar.getInstance(Locale.US);
Upvotes: 4