a flutter package for using jalali (shamsi, solar, persian, شمسی or خورشیدی) date. you can convert, format and manipulate jalali and georgian dates.
this is a pure dart package and algorithm is based on popular javascript library jalaali-js with more than 20k monthly downloads.
this package has a lot of unit tests with high test coverage for ensuring its correctness.
key features
- convert between jalali, gregorian and flutter’s datetime objects.
- access year, month, day, weekday, julian day number, month length and … through getters.
- format jalali and georgian dates with an easy and powerful syntax using dateformatter.
- ensure jalali and georgian dates validity.
- check if a jalali or gregorian year is leap.
- immutable date objects with copy methods for easy manipulation.
- compare dates easily with comparison operators or by using comparable.
- add or subtract days with
+
and-
operators. - find distance between dates by methods and
^
operator. - add years, months and days separately or as a combination with methods.
- high code coverage with a lot of unit tests.
- null-safe api
recent changes
as of version 0.16.0
toutcdatetime
method is added and todatetime` has more functionality.
issues and feature requests
if you want a new feature, or you found an issue, please make an issue on github, so i can see your request.
usage
add it to your pubspec.yaml file:
dependencies:
shamsi_date: ^latest.version
then depend on it:
import 'package:shamsi_date/shamsi_date.dart';
if you want extension methods, also depend on extensions:
import 'package:shamsi_date/extensions.dart';
jalali class is used for shamsi (jalali, persian, شمسی or خورشیدی) date and gregorian class is used for gregorian (miladi or میلادی) date. jalali and gregorian classes are the subclasses of date.
jalali and gregorian can be instantiated with providing year
, month
and day
among other ways:
jalali j = jalali(year, month, day);
gregorian g = gregorian(year, month, day);
month and day has default value of 1
if you don’t specify them, so jalali(year, month)
is equivalent to jalali(year, month, 1)
and gregorian(year)
is equivalent to gregorian(year, 1, 1)
.
constructor arguments should be non-null or exception will be thrown immediately. this ensures objects being in valid state when created. so year, month and day are always non-null. almost all methods, operators, constructors and factories should have non-null arguments, and they will return non-null objects. for example year, month and day getters will return non-null results. the only exception for methods which can accept null arguments are methods with optional arguments like add(...)
and copy(...)
. in nullsafe version: nullable and non-nullable argument and return types are checked statically.
all created date instances are valid. when creating a date instance either by using constructors and factories or by using methods and operators on an existing date instance, if the new date is invalid (by its month or day being out of range), or it is out of computable range, a dateexception exception is thrown. so if you think the new date instance can become invalid or out of range you should surround it with try-catch and catching dateexception
. minimum computable date is gregorian(560,3,20)
or equivalently jalali(-61,1,1)
and maximum computable date is gregorian(3798,12,31)
or equivalently jalali(3177,10,11)
. for example:
void main() {
try {
jalali jv = jalali(1398, 13, 1); // not valid!
} on dateexception catch (e) {
// prints: dateexception: jalali month is out of valid range.
print(e);
}
}
jalali and gregorian objects are immutable. so using operators and methods will give you new object and does not manipulate the object in place, like string objects. almost all other objects in shamsi_date library are immutable too.
you can access year
, month
, day
through getters on jalali or gregorian dates. you can get week day number of jalali and gregorian by using weekday
getter. week days range from 1 to 7. jalali week starts with shanbe
and gregorian week starts with monday
. month length can be accessed using monthlength
getter. month length is sensitive to leap years. you can check if the year is a leap year by isleapyear()
method. julian day number is also accessible through juliandaynumber
getter. for example:
jalali j = jalali(1397, 5, 6);
int jy = j.year; // jy = 1397
int jm = j.month; // jm = 5
int jd = j.day; // jd = 6
int wd = j.weekday; // wd = 1 (shanbe)
// month length of 1397/5
// note: day value is not important for monthlength
int ml = j.monthlength; // ml = 31
// check if 1397 is a leap year
// note: month and day values are not important for isleapyear() method
bool ly = j.isleapyear(); // ly = false (1397 is not leap year)
// and equivalently for gregorian date objects ...
you can convert jalali dates to gregorian by using togregorian()
method and convert gregorian to jalali date by using tojalali()
method. there are also factory methods jalali.fromgregorian(...)
and gregorian.fromjalali(...)
which can be used alternatively.
jalali j = jalali(1397, 5, 6);
// convert to gregorian:
gregorian j2g1 = j.togregorian(); // -> 2018/8/28
// or equivalently:
gregorian j2g2 = gregorian.fromjalali(j);
gregorian g = gregorian(2019, 10, 26);
// convert to jalali:
jalali g2j1 = g.tojalali(); // -> 1398/8/4
// or equivalently:
jalali g2j2 = jalali.fromgregorian(g);
you can convert datetime objects directly to jalali or gregorian dates by using fromdatetime(datetime)
static methods. convert jalali and gregorian to datetime by using todatetime()
method. you can pass hour
, minute
and other time details to arguments. there is also toutcdatetime
for utc date times. get jalali and gregorian dates for now by using now()
factory.
// convert from datetime
jalali j = jalali.fromdatetime(datetime);
gregorian g = gregorian.fromdatetime(datetime);
// convert to datetime
datetime j2dt = j.todatetime();
datetime g2dt = g.todatetime();
// you can also add hour, minute, ...
datetime j2dt1 = j.todatetime(13, 25, 48);
// and also convert to utc:
datetime j2dt2 = j.toutcdatetime(13, 25, 48);
// get now
jalali jnow = jalali.now();
gregorian gnow = gregorian.now();
for converting datetime you can also use extension methods.
datetime dt = datetime.now();
jalali j = dt.tojalali();
gregorian g = dt.togregorian();
jalali and georgian dates are immutable, so you can not change their properties in place. if you want only to change some fields of a jalali or gregorian date you can use copy(...)
method or withyear
, withmonth
and withday
methods on an existing object. these methods can be chained. copy method changes all fields at one. note that copy and with*() methods are not safe, and it is your responsibility to avoid problems like month length bound (for example changing month of 31 farvardin 1390
to esfand
) or leap crash (for example being in last day of year in a leap year and changing year to a non-leap one) in intermediate steps. order of operations is important.
for example for getting date at start of this month in jalali: (copy method makes another object instance and leaves the original one unchanged)
jalali j1 = jalali.now().withday(1); // correct way
// or by using copy method:
jalali j2 = jalali.now().copy(day: 1); // also correct
// don not do it like this:
jalali j3 = jalali(jalali.now().year, jalali.now().month, 1); // incorrect
or if you want to get last day of the last month of this jalali year:
// at first go to first day of last month: (avoid leap crash)
jalali tmp = jalali.now().withday(1).withmonth(12);
// since we can be in a leap year we use monthlength for going to last day:
jalali j = tmp.withday(tmp.monthlength);
// or by using copy method:
jalali tmp1 = jalali.now().copy(month: 12, day: 1);
jalali j1 = tmp.copy(day: tmp1.monthlength);
or to find 3rd day of 2nd month of this year:
jalali j = jalali.now().withday(3).withmonth(2);
// or by using copy method:
jalali j1 = jalali.now().copy(month: 2, day: 3);
or if you want your jalali and gregorian objects to fall back to today if null is provided as their constructor arguments you can use copy method from now factory method, for example for jalali:
jalali j = jalali.now().copy(year: y, month: m, day: d);
// y, m and d can be null
you can find distance between jalali and gregorian dates by using ^
operator. note that -
operator is for something else. or you can use distanceto
and distancefrom
methods.
int distance11 = jalali.now() ^ jalali(1395, 10, 1);
// or
int distance12 = jalali.now().distancefrom(jalali(1395, 10, 1));
// or
int distance13 = jalali(1395, 10, 1).distanceto(jalali.now());
// and similarly for gregorian
int distance2 = gregorian(2021) ^ gregorian(2020);
you can add and subtract days to jalali and gregorian using +
and -
operators. it is guaranteed to give you a bound valid date. for example, it will go to next month or next year if needed, and they won’t have leap crash.
you can add years, months or days to jalali and gregorian using addyears
, addmonths
and adddays
. these methods can be chained, and they will not have range crash. adddays
can change month and year. addmonths
can change year. note that it is your responsibility to avoid leap crash.
if you want you can add a combination of days, months or years to a date object with add
method. note that add
method is not safe and does not manipulate result to become bound valid, it is your responsibility. it is recommended to use addyear, addmonth and addday methods over add method. note by using addyears, addmonth and addday you can put day out of month length bounds. addmonth is safe for month overflow.
jalali j1 = jalali(1398, 8, 4);
// add days
jalali j2 = j1 + 3; // -> 1398/8/7
// result will be manipulated to become valid:
jalali j3 = j1 + 30; // -> 1398/9/4
jalali j4 = j1 + 365; // -> 1399/8/4
// subtract days
jalali j5 = j1 - 2; // -> 1398/8/2
// add years, months and days:
jalali j6 = j1.addyears(1).addmonths(2).adddays(3); // 1399/10/7
// or:
jalali j60 = j1.add(years: 1, months: 2, days: 3); // 1399/10/7
// add years and days only:
jalali j7 = j1.addyears(1).adddays(3); // 1399/8/7
// or:
jalali j70 = j1.add(years: 1, days: 3); // 1399/8/7
// add months only:
jalali j8 = j1.addmonths(2); // 1398/10/3
// or:
jalali j80 = j1.add(months: 2); // 1398/10/3
// if you want to subtract you can add negative value:
jalali j9 = j1.addyears(-1); // 1397/8/3
// or:
jalali j90 = j1.add(years: -1); // 1397/8/3
// addyears, addmonths and adddays methods are bound safe
// add(...) method is not bound safe
date formatting is easy. you should make a function for custom formatting and then pass your jalali or gregorian dates to this function.
for example if you want to format as weekdayname day monthname twodigityear
you make a function for it:
string format1(date d) {
final f = d.formatter;
return '${f.wn} ${f.d} ${f.mn} ${f.yy}';
}
// example output for jalali: "پنج شنبه 21 دی 91"
// example output for gregorian: "thursday 10 january 13"
or if you want to format as fourdigityear/twodigitmonth/twodigitday
or yyyy/mm/dd
, you make a function for it:
string format2(date d) {
final f = d.formatter;
return '${f.yyyy}/${f.mm}/${f.dd}';
}
then use it like before.
note that formatter formats digits in english so if you want persian digits you can use fonts with persian digits or apply a simple mapping to formatter output to change english digits to persian.
jalali and georgian dates support tostring()
method. for jalali, it is semantically equivalent to use a formatter as jalali(y,m,d)
which means:
string tostringformatter(jalali d) {
final f = d.formatter;
return 'jalali(${f.y},${f.m},${f.d})';
}
for georgian, tostring() is equivalent to using a formatter as georgian(y,m,d)
.
note: in the following code tostring() is called implicitly:
void main() {
print(jalali.now());
final str = 'today is: ${georgian.now()}';
}
use tostring() of jalali and georgian dates only for development purpose, like for debugging, logging or … you should use formatters for showing dates on the ui.
note also that you do not need for example to use int.parse()
on formatter output of jalali.now().formatter.m
for accessing its month, simply use jalali.now().month
.
dateformatter has these getters:
- y: year (whatever length it has). year should be positive.
- yy: two digit year. year should be between 1000 and 9999.
- yyyy: four digit year. year should be between 0 and 9999.
- m: month (whatever length it has).
- mm: two-digit month.
- mn: month name.
- d: day (whatever length it has).
- dd: two digit day.
- wn: week day name.
you can get date formatter by using formatter
getter on jalali and gregorian date objects. simply cash this formatter in a jalali value and then use string interpolation (as we have shown in examples) for making your desired output. this way of formatting is more powerful (and arguably easier) than using templates.
jalali and gregorian classes are comparable so you can compare them using compareto
method. you can also use comparison operators to compare them. they also support equals
and hashcode
functions. so you can safely use sets and maps of jalali and gregorian dates.
jalali j1 = jalali(1397, 1, 1);
jalali j2 = jalali(1397, 2, 1);
bool b1 = j1 < j2; // b1 = true
bool b2 = j1 >= j2; // b2 = false
// using comparable compareto
bool b3 = j1.compareto(j2) > 0; // b3 = false (means j1 > j2 is false)
bool b4 = j1.compareto(j2) <= 0; // b4 = true (means j1 <= j2 is true)
bool b5 = j1 == j2; // b5 = false
bool b6 = j1 != j2; // b6 = true
example
here is a complete example. if you did not find what you are looking for, you can check test/shamsi_date_test.dart
file which includes unit tests.
import 'package:shamsi_date/shamsi_date.dart';
import 'package:shamsi_date/extensions.dart';
void main() {
// gregorian to jalali conversion
gregorian g1 = gregorian(2013, 1, 10);
jalali j1 = g1.tojalali();
print('$g1 == $j1');
// prints: gregorian(2013,1,10) == jalali(1391,10,21)
// you can write jalali.fromgregorian(g1) instead of g1.tojalali()
// access year, month and day through getters
// for jalali:
int j1y = j1.year; // j1y = 1391
int j1m = j1.month; // j1m = 10
int j1d = j1.day; // j1d = 21
print('j1 is $j1y-$j1m-$j1d'); // prints: j1 is 1397-10-21
// note: use formatters for formatting dates
// and for gregorian:
int g1y = g1.year; // g1y = 2013
int g1m = g1.month; // g1m = 1
int g1d = g1.day; // g1d = 10
print('g1 is $g1y-$g1m-$g1d'); // prints: g1 is 2013-1-10
// note: use formatters for formatting dates
// jalali to gregorian conversion
jalali j2 = jalali(1391, 10, 21);
gregorian g2 = j1.togregorian();
print('$j2 == $g2');
// prints: jalali(1391,10,21) == gregorian(2013,1,10)
// also can use gregorian.fromjalali(j1) instead of j1.togregorian()
// find weekday
print('$j1 has weekday ${j1.weekday}'); // -> 6
// 6 means "پنج شنیه"
print('$g1 has weekday ${g1.weekday}'); // -> 4
// 4 means "thursday"
// find month length
print('jalali 1390/12 month length? '
'${jalali(1390, 12).monthlength}'); // -> 29
print('gregorian 2000/2 month length? '
'${gregorian(2000, 2).monthlength}'); // -> 29
// check leap year
print('1390 jalali is leap year? '
'${jalali(1390).isleapyear()}'); // -> false
print('2000 gregorian is leap year? '
'${gregorian(2000).isleapyear()}'); // -> true
// validity:
// all created instances are considered valid
// if you think a date might invalid, use try-catch:
try {
jalali jv = jalali(1398, 13, 1); // not valid!
print(jv); // this line is not reached
} on dateexception catch (e) {
// prints: dateexception: jalali month is out of valid range.
print(e);
}
// making leap crash will also throw exception:
// for ex: jalali(1394, 12, 30) will crash, since
// 1394 is not leap year
// creating dates out of computable range also throws dateexception.
// convert datetime object to jalali and gregorian
datetime datetime = datetime.now();
print('now is $datetime');
print('now is ${gregorian.fromdatetime(datetime)} in gregorian');
print('now is ${jalali.fromdatetime(datetime)} in jalali');
// convert to datetime
print('$j1 is ${j1.todatetime()}');
print('$g1 is ${g1.todatetime()}');
// convert jalali and gregorian to datetime
print('$j1 as datetime is ${j1.todatetime()}');
print('$g1 as datetime is ${g1.todatetime()}');
// find today with now() factory method
print('now is ${gregorian.now()} in gregorian');
print('now is ${jalali.now()} in jalali');
// find out which jalali year is this year:
int thisjalaliyear = jalali.now().year;
print('this jalali year is $thisjalaliyear');
// copy method
print('$j1 with year = 1300 is ${j1.copy(year: 1300)}');
// prints: 1391/10/21 with year = 1300 is 1300/10/21
print('$g1 with month = 1 and day = 2 is ${g1.copy(month: 1, day: 2)}');
// prints: 2013/1/10 with month = 1 and day = 2 is 2013/1/2
// withyear, withmonth and withday methods:
// these methods can be chained
// it is recommended to use these methods over copy method
print('$j1 with year = 1300 is ${j1.withyear(1300)}');
// prints: 1391/10/21 with year = 1300 is 1300/10/21
print('$g1 with month = 1 and day = 2 is ${g1.withday(2).withmonth(1)}');
// prints: 2013/1/10 with month = 1 and day = 2 is 2013/1/2
// for example for getting date at start of this month in jalali:
print(jalali.now().copy(day: 1));
// for example to find 3rd day of 2nd month of this year:
print(jalali.now().copy(month: 2, day: 3));
// don not do it like this:
print(jalali(jalali.now().year, jalali.now().month, 1)); // incorrect
// for example if you want to get
// the last day of the last month of this jalali year:
jalali tmp = jalali.now().copy(month: 12, day: 1);
// since we can be in a leap year we use monthlength:
print(tmp.copy(day: tmp.monthlength));
// add and subtract days
jalali d1 = jalali(1398, 8, 4);
// add days
print(d1 + 3); // -> 1398/8/7
// result will be manipulated to become valid:
print(d1 + 30); // -> 1398/9/4
print(d1 + 365); // -> 1399/8/4
// subtract days
print(d1 - 2); // -> 1398/8/2
// add years, months and days:
print(d1.add(years: 1, months: 2, days: 3)); // 1399/10/7
// add years and days only:
print(d1.add(years: 1, days: 3)); // 1399/8/7
// add months only:
print(d1.add(months: 2)); // 1398/10/3
// if you want to subtract you can add negative value:
print(d1.add(years: -1)); // 1397/8/3
// and also for gregorian
// you can find distance between two days with "^" operator
int distance11 = jalali.now() ^ jalali(1395, 10);
int distance12 = jalali.now().distancefrom(jalali(1395, 10));
int distance13 = jalali(1395, 10).distanceto(jalali.now());
print('distance $distance11 $distance12 $distance13');
// and similarly for gregorian
// or you can use addyears, addmonths and adddays method
// it is recommended to use these methods over add method
// these methods are bound valid which means result will be
// manipulated to become valid, but add method is not
print(d1.adddays(30)); // -> 1398/9/4
print(d1.adddays(365)); // -> 1399/8/4
print(d1.addyears(1).addmonths(2).adddays(3)); // 1399/10/7
print(d1.addyears(1).adddays(3)); // 1399/8/7
print(d1.addmonths(2)); // 1398/10/3
print(d1.addyears(-1)); // 1397/8/3
// formatting examples:
// example one:
string format1(date d) {
final f = d.formatter;
return '${f.wn} ${f.d} ${f.mn} ${f.yy}';
}
print(format1(j1)); // prints: پنج شنبه 21 دی 91
print(format1(g1)); // prints: thursday 10 january 13
// example one:
string format2(date d) {
final f = d.formatter;
return '${f.dd}/${f.mm}/${f.yyyy}';
}
print(format2(j1)); // prints: 21/10/1391
print(format2(g1)); // prints: 10/01/2013
// do not use formatter for accessing year, month or other properties
// of date objects they are available as getters on date objects
// incorrect example, do not use this:
int j1y1 = int.parse(j1.formatter.yyyy); // incorrect
print("j1's year is $j1y1");
// use this:
int j1y2 = j1.year; // correct
print("j1's year is $j1y2");
// also using tostring() for showing dates on ui is not recommended,
// use custom formatter.
// comparing dates examples:
print(j1 > j2); // -> false
print(j1.compareto(j2) > 0); // -> false
print(j1 <= j2); // -> true
print(j1.compareto(j2) <= 0); // -> true
print(g1 >= g2); // -> true
print(g1.compareto(g2)); // -> 0
print(g1 == g2); // -> true
print(g1 != g1); // -> false
// if you want to compare jalali with georgian
// you can convert one type to another,
// for example:
print(j1.togregorian() == g1); // -> true
// but if you don't want to convert them you can use juliandaynumber
// (this approach is not recommended)
print(j1.juliandaynumber == g1.juliandaynumber); // -> true
// this means that they are equal
// you can also use other comparison operators
// you can use extension methods for datetime
final dtn = datetime.now();
print(dtn);
final jn = dtn.tojalali();
print(jn);
final gn = dtn.togregorian();
print(gn);
}
Comments are closed.