是否可以本地化Java日历类以将当前系统日期转换为例如Jalali(波斯)日期?
例如,创建实例时,您可以传递Locale
。
Calendar.getInstance(Locale.US);
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.