I want to convert Gregorian (western) date to Persian (Shamsi) date and vice versa for all versions of Android.
Is there any complete and reliable library or algorithm?
I want to convert Gregorian (western) date to Persian (Shamsi) date and vice versa for all versions of Android.
Is there any complete and reliable library or algorithm?
Try this
create instance
You may use this stable and tested library with a formatter class, Roozh for Java. It's not deprecated and always getting updated with cool features which Persian date time needs.
Use IBM's International Components for Unicode (icu4j). It is part of Unicode Consortium, is extremely reliable and can be used in any java project (Java EE, Java SE, Android, etc). Use it with Gradle, Maven or simply by downloading the jar.
TL;DR
Usage:
Output:
More detailed:
Java 7 and before:
You can expect all of functionalities of
java.util.Calendar
in addition to some other ones:WARNING: Note that month field is zero based in Java calendar so by
calendar.set(1395, 3, 10)
calendar will represent 4th month of 1395, not 3rd!If you need text outputs in persian:
Output:
If you need output to be in english, change
new ULocale("fa_IR@calendar=persian")
tonew ULocale("@calendar=persian")
.Output:
Other nice things:
For other functionalities see icu4j demos, specially:
fa_IR
for locale)Also see Calendar and PersianCalendar API.
Java 8 onward:
In order to use
java.time
classes likeZonedDateTime
orLocalDateTime
, you could simply use this methods to convert a persian date to preferred classes:Remarks About Jar Size
If you're concerned about icu4j's jar size , then you may rebuild it and just use the Calendar module (2,176KB). More Info: ver. 57 or earlier , ver. 58 or later using ICU Data Build Tool.
There is persianutils project which includes a bi-directional DateConverter; Gregorian <-> Persian (Jalali). It is written in Scala, so I suppose using it in a Java project would be quite easy.
The algorithm used is valid for Gregorian years up to ~3790 and Persian years up to ~3170.
DISCLAIMER: I am the author of PersianUtils
Beside Time4A, icu4j, which are too heavy libraries, I written a class to handle Persian calendar accurately and you can find it here: https://github.com/hadilq/java-persian-calendar/blob/master/persian/src/main/java/ir/hadilq/PersianCalendar.java
As you can find it in its tests, this class supports from year 3000 before hijra to 3000 after hijra.
I'm using this algorithm for years and it is very accurate between 1901 and 2099.
Use it and Enjoy! :)