title: Java - convert current date into UTC and UTC in any TimeZone
body: <p>I need two things:</p>
  
  <ol>
  <li><p>convert current time into UTC (so I can store date in UTC format)
  --> <strong>result = java.util.Date.</strong></p></li>
  <li><p>convert loaded date (UTC format) into any TimeZone --> <strong>result =
  java.util.Date or milliseconds</strong>.</p></li>
  </ol>
  
  <p>For both points bear daylight in mind.</p>
  
  <p>1)
  I found following on stackoverflow:</p>
  
  <pre><code>Calendar c = Calendar.getInstance();
  System.out.println("current: "+c.getTime());
  
  TimeZone z = c.getTimeZone();
  int offset = z.getRawOffset();
  if(z.inDaylightTime(new Date())){
      offset = offset + z.getDSTSavings();
  }
  int offsetHrs = offset / 1000 / 60 / 60;
  int offsetMins = offset / 1000 / 60 % 60;
  
  System.out.println("offset: " + offsetHrs);
  System.out.println("offset: " + offsetMins);
  
  c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
  c.add(Calendar.MINUTE, (-offsetMins));
  
  System.out.println("GMT Time: "+c.getTime());
  </code></pre>
  
  <p>--> result equals UTC?</p>
  
  <p>2)</p>
  
  <pre><code>public static long getTimeMillisFromTimeZone(long utcTimeMillis,
          String timeZoneId) {
      System.out.println("input millis: " + utcTimeMillis);
      Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
      calendar.setTimeInMillis(utcTimeMillis);
      TimeZone fromTimeZone = calendar.getTimeZone();
      TimeZone toTimeZone = TimeZone.getTimeZone(timeZoneId);
  
      calendar.setTimeZone(fromTimeZone);
      calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
      if (fromTimeZone.inDaylightTime(calendar.getTime())) {
          calendar.add(Calendar.MILLISECOND, calendar.getTimeZone()
                  .getDSTSavings() * -1);
      }
  
      calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
      if (toTimeZone.inDaylightTime(calendar.getTime())) {
          calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
      }
  
      System.out.println(calendar.getTime());
  
      System.out.println("output millis: " + calendar.getTime().getTime());
      return calendar.getTime().getTime();
  }
  </code></pre>
  
  <p>--> I got a problem there --> lost 1h!</p>
  
  <p>In my example I stored a Date from TimeZone "Europe/Vienna" (using daylight) into database as utc.
  Europa/Vienna --> 10:00
  UTC --> 09:00</p>
  
  <p>Now I want to convert this UTC (09:00) into "Europe/Vienna" and I get: 09:00 = I lost an hour..</p>