Search code examples
javaandroiddeprecatedjulian-date

Problems with alternative to Time.julianDay


I'm trying to update my old code, but I have some problems updating Time.getJulianDay. I have tried to use GregorianCalendar, but I can't transform it to an int. ¿Is there any way to do it?

This is my code:

public void addDate(ExtendedCalendarView calendarView,String eventname,String description, String location)
{
    try {
        if(startYear==-1)
            throw new Exception("No has indicado los valores de las horas");

        cal.set(startYear, startMonth - 1, startDay, startHour, startMinute);
        long time = cal.getTimeInMillis();

        ContentValues values = new ContentValues();
        values.put(CalendarProvider.COLOR, Event.COLOR_RED);
        values.put(CalendarProvider.DESCRIPTION, description);
        values.put(CalendarProvider.LOCATION, location);
        values.put(CalendarProvider.EVENT, eventname);
        values.put(CalendarProvider.START, time);
        values.put(CalendarProvider.START_DAY, getJulianDay(time));

        cal.set(stopYear, stopMonth - 1, stopDay, stopHour, stopMinute);
        time = cal.getTimeInMillis();
        values.put(CalendarProvider.END, time);
        values.put(CalendarProvider.END_DAY, getJulianDay(time));

        context.getContentResolver().insert(CalendarProvider.CONTENT_URI, values);

        restartTime();
        calendarView.refreshCalendar();

    }
    catch (Exception ex)
    {
        Log.d("asd", "ERROR;"+ex.getMessage());
    }

}

private int getJulianDay(long time)
{
    GregorianCalendar date=(GregorianCalendar) GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
    date.setTime(new Date(time));
    date.set(Calendar.HOUR_OF_DAY, 0);
    date.set(Calendar.MINUTE,0);
    date.set(Calendar.SECOND, 0);
    date.set(Calendar.MILLISECOND,0);


    //return Time.getJulianDay(time, TimeUnit.MILLISECONDS.toSeconds(timeZone.getOffset(time)));
}

Thanks


Solution

  • Have you considered using the JodaTime library in your app? It will make working with date/time on Android much easier. The helper functions toJulianDay() and toJulianDayNumber() would be perfect for what you are trying to do. Those methods return double and long respectively and you can cast or convert the result to an int if it's absolutely needed (but you will be losing some precision).

    The toJulianDay(long) method calculates the astronomical Julian Day with a fraction based on days starting at midday. This method calculates the variant where days start at midnight. JDN 0 is used for the date equivalent to Monday January 1, 4713 BC (Julian). Thus these days start 12 hours before those of the fractional Julian Day.

    Here is the full documentation for more details. and a link to the JodaTime project.