Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java GregorianCalendar

Tags:

java

timezone

I'm trying to understand GregorianCalendar learning java as a seasoned Delphi (pascal) developer. According to the documentation, January 1, 1970 at 0:00:00 is the reference for calculating time elapsed in seconds from this point. So, in experimenting, I set a new variable

GregorianCalendar cal2 = new GregorianCalendar(1970, 0, 1, 0, 0, 0); //January=0, Day=1, Hour=0, Min=0, Sec=0

then I read the time

cal2.getTimeInMillis()

This should equal zero by definition. Yet I get 18,000,000 milliseconds. This is 5 hours. I am thinking this has to do with the time zone? Any suggestions, I am on Eastern Zone.

If so, how do I account for this? I am really trying to understand so I can calculate differences in seconds between two times. Without understanding this, I can't proceed! Thanks! Doug

like image 976
douglas keene Avatar asked Jun 21 '26 18:06

douglas keene


1 Answers

package so;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class BeginningOfTime {

  public static void main (final String[] args) {

    final Calendar localTZ = new GregorianCalendar (1970, 0, 1, 0, 0, 0);
    dump (localTZ);

    final Calendar utcTZ = new GregorianCalendar ();
    utcTZ.clear ();
    utcTZ.setTimeZone (TimeZone.getTimeZone ("UTC"));
    dump (utcTZ);
  }

  private static final void dump (final Calendar c) {

    System.out.printf ("%s: %d (offset %d)%n",
                       c.getTimeZone ().getDisplayName (),
                       c.getTimeInMillis (),
                       c.get (Calendar.ZONE_OFFSET));
  }
}

Yields this:

Eastern Standard Time: 18000000 (offset -18000000)
Coordinated Universal Time: 0 (offset 0)
like image 183
carej Avatar answered Jun 24 '26 07:06

carej



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!