0

I'm Creating a Calendar of type GregorianCalendar and setting it to my timezone (GMT+12) Then I literally set the time from strings for hour and minute eg "06" "37" Then display the time in ms If I do this with the device time set before midnight The timeinms then equates to 6:37PM , should be AM

However, if I do this after midnight the timeinms equates to 6:37AM, which is correct

My Code is as follows

public Calendar getTime (Location Loc, String definition)
{


    Calendar event = new GregorianCalendar(TimeZone.getTimeZone("NZ"));

  int DD = event.get(Calendar.DAY_OF_MONTH);
  int MM = event.get(Calendar.MONTH)+1;
  int YY = event.get(Calendar.YEAR);
    String HH="";
    String mm="";

String CivilSunrise ="06:37"

if (definition=="sunrise"){
        HH = CivilSunrise.substring(0,2); // 06
        mm = CivilSunrise.substring(3,5); // 37
    }

    if (definition=="sunset"){
        HH = CivilSunset.substring(0,2);
        mm = CivilSunset.substring(3,5);
    }

    Long before = event.getTimeInMillis(); 

    event.set(Calendar.HOUR,Integer.parseInt(HH));
    event.set(Calendar.MINUTE,Integer.parseInt(mm));

    Long after = event.getTimeInMillis();


return event;

}

Why is this happening, obviously the date changes after midnight but surely the time added to the Calendar object by string should be the number of hours from midnight

time backwards to wed 6th may 23:41

23:53 sunrise     output millis: Wed May 06 18:37:37 GMT+12:00 2020
23:52:46.661     output hours 2020-05-06T06:37:37.631Z

23:55 sunset      output millis: Thu May 07 05:54:57 GMT+12:00 2020
                  output hours 2020-05-06T17:54:57.284Z
the output for millis is incorrect, the output for hours is correct

Now I set the android time Forwards to 1:00AM 7/5/2020

sunrise      output millis: Thu May 07 06:38:46 GMT+12:00 2020
             output hours 2020-05-06T18:38:46.737Z

sunset       output millis: Thu May 07 17:53:24 GMT+12:00 2020
             output hours2020-05-07T05:53:24.384Z

now the output for millis is correct, the output for hours is incorrect the logs are produced with

Log.d("sun","output millis: " + event.getTime());
    Log.d("sun","output hours" + event.getTime().toInstant());
james
  • 113
  • 1
  • 1
  • 10
  • 2
    By the way, `NZ` is not a real time zone name. Use `Pacific/Auckland` for New Zealand. – Basil Bourque May 06 '20 at 15:08
  • 2
    Never use `Calendar`. Supplanted years ago by the modern *java.time* classes. For Android < 26, use *ThreeTenABP* back-port. `ZonedDateTime.now( ZoneId.of( "Pacific/Auckland" ) ).with( LocalTime.of( 6 , 37 ).toInstant().toEpochMilli()` – Basil Bourque May 06 '20 at 15:12

0 Answers0