eloyzone / jalali-calendar

A java Library that converts Gregorian to Jalali (or Jalali to Gregorian)
GNU Lesser General Public License v3.0
35 stars 4 forks source link

One month and one day behind #1

Closed mohsentaheris closed 3 years ago

mohsentaheris commented 3 years ago

Today is 1399-10-17 but following code returns 1399-09-16

DateConverter dateConverter = new DateConverter(); Calendar calendar = Calendar.getInstance(); JalaliDate jalaliDate = dateConverter.gregorianToJalali(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); System.out.println(jalaliDate.format(new JalaliDateFormatter("yyyy-mm-dd", JalaliDateFormatter.FORMAT_IN_ENGLISH)));

eloyzone commented 3 years ago

Today is 1399-10-17 but following code returns 1399-09-16

DateConverter dateConverter = new DateConverter(); Calendar calendar = Calendar.getInstance(); JalaliDate jalaliDate = dateConverter.gregorianToJalali(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); System.out.println(jalaliDate.format(new JalaliDateFormatter("yyyy-mm-dd", JalaliDateFormatter.FORMAT_IN_ENGLISH)));

Well, the problem is that you are using an instance of Calendar, which is zero based and you need to increment the value of calendar.get(Calendar.MONTH) by one (why??). It's better to use LocalDate which is the evolved version of Calendar and it's highly recommended after Java8.

Let me show you the differences:

Calendar calendar = Calendar.getInstance(); LocalDate localDate = LocalDate.now();

System.out.println(calendar.get(Calendar.YEAR) + "/" + calendar.get(Calendar.MONTH) + "/" + calendar.get(Calendar.DAY_OF_MONTH));

System.out.println(localDate.getYear() + "/" + localDate.getMonthValue()+ "/" + localDate.getDayOfMonth());

The output would be: 2021/0/6 2021/1/6

The correct code you are looking for is:

DateConverter dateConverter = new DateConverter(); LocalDate localDate = LocalDate.now(); JalaliDate jalaliDate = dateConverter.gregorianToJalali(localDate.getYear(), localDate.getMonthValue(), localDate.getDayOfMonth()); System.out.println(jalaliDate.format(new JalaliDateFormatter("yyyy-mm-dd", JalaliDateFormatter.FORMAT_IN_ENGLISH)));

mohsentaheris commented 3 years ago

Thanks for your feedback I will change it to LocalDate instead of Calendar.