Search code examples
javacalendarhijri

Get Hijri date from future Gregorian date


How am I able to get hijradate from the code below but instead of now() I would like to get this from a future date.

java.time.chrono.HijrahDate hijradate = java.time.chrono.HijrahDate.now();
System.out.println("hijradate "+hijradate);

Solution

  • It’s straightforward when you know how:

        LocalDate gregorianDate = LocalDate.of(2019, Month.FEBRUARY, 22);
        HijrahDate hijradate = HijrahDate.from(gregorianDate);
        System.out.println(hijradate);
    

    This printed

    Hijrah-umalqura AH 1440-06-17
    

    If by Gregorian date you meant that you had your date in a GregorianCalendar object (typically from a legacy API that you cannot change or don’t want to change just now):

        GregorianCalendar gregCal = // ...
    
        ZonedDateTime gregorianDateTime = gregCal.toZonedDateTime();
        System.out.println(gregorianDateTime);
        HijrahDate hijradate = HijrahDate.from(gregorianDateTime);
        System.out.println(hijradate);
    

    Output in one run on my computer was:

    2019-02-22T00:00+03:00[Asia/Riyadh]
    Hijrah-umalqura AH 1440-06-17
    

    EDIT: For the sake of completeness here are my imports so you know exactly which classes I am using:

    import java.time.LocalDate;
    import java.time.Month;
    import java.time.ZoneId;
    import java.time.ZonedDateTime;
    import java.time.chrono.HijrahDate;
    import java.util.GregorianCalendar;
    

    EDIT: To get the month: use your search engine. I used mine and found:

        int month = hijradate.get(ChronoField.MONTH_OF_YEAR);
        System.out.println(month);
        String formattedMonthName 
                = hijradate.format(DateTimeFormatter.ofPattern("MMMM", new Locale("ar")));
        System.out.println(formattedMonthName);
    

    This prints

    6
    جمادى الآخرة
    

    The last lines are inspired from this answer.