Labels

Thursday, August 16, 2012

ConvertTimeZone

Método simples para converter hora de um TimeZone para outro.

package br.com.blogspot.rozolin.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DataUtils {
 
 private DataUtils(){}
 
 
 public static void main(String[] args) {
//  pega o timezone local da maquina (UTC-03:00)
  TimeZone local = TimeZone.getDefault();
//  pega o timezone Greenwich (UTC 00:00)  
  TimeZone greenwich = TimeZone.getTimeZone("Greenwich");

  Date agoraLocal = new Date();
  
  Date agoraGreenwich  = convertTimeZone(agoraLocal, local, greenwich);
  
  SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
  
  System.out.println(local.getDisplayName());
  System.out.println(sdf.format(agoraLocal));
  
  System.out.println(greenwich.getDisplayName());
  System.out.println(sdf.format(agoraGreenwich));
 }


 public static Date convertTimeZone(Date data, TimeZone de,
   TimeZone para) {
  
  return new Date(data.getTime() - de.getRawOffset() + para.getRawOffset());
 }

}

Saída:
Fuso horário de Brasília
16/08/2012 21:01
Fuso horário do meridiano de Greenwich
17/08/2012 00:01

No comments:

Post a Comment