2012-05-15 29 views
12
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); 
java.util.Date fromDate = cal.getTime(); 
System.out.println(fromDate); 

El código anterior no imprime la fecha en GMT, sino que se imprime en la zona horaria local. ¿Cómo consigo una fecha equivalente GMT desde la fecha actual (suponiendo que el programa puede funcionar en Japón o SFO)Cómo convertir una fecha local a GMT

Respuesta

20

¿Qué tal esto -

public static void main(String[] args) throws IOException { 
    Test test=new Test(); 
    Date fromDate = Calendar.getInstance().getTime(); 
    System.out.println("UTC Time - "+fromDate); 
    System.out.println("GMT Time - "+test.cvtToGmt(fromDate)); 
} 
private Date cvtToGmt(Date date){ 
    TimeZone tz = TimeZone.getDefault(); 
    Date ret = new Date(date.getTime() - tz.getRawOffset()); 

    // if we are now in DST, back off by the delta. Note that we are checking the GMT date, this is the KEY. 
    if (tz.inDaylightTime(ret)){ 
     Date dstDate = new Date(ret.getTime() - tz.getDSTSavings()); 

     // check to make sure we have not crossed back into standard time 
     // this happens when we are on the cusp of DST (7pm the day before the change for PDT) 
     if (tz.inDaylightTime(dstDate)){ 
      ret = dstDate; 
     } 
    } 
    return ret; 
} 

Prueba Resultado:
tiempo UTC - mar 15 may 2012 16:24:14 IST
Hora GMT - Tue May 15 10:54:14 CEST 2012

+0

Muchas gracias. Me ayuda –

+0

da la bienvenida @HaiderAli :) –

15
DateFormat gmtFormat = new SimpleDateFormat(); 
TimeZone gmtTime = TimeZone.getTimeZone("GMT"); 
gmtFormat.setTimeZone(gmtTime); 
System.out.println("Current DateTime in GMT : " + gmtFormat.format(new Date())); 

más general que puede convertir a cualquier zona horaria (válido) de esta manera


Ver

+1

gmtFormat.format (new Date()) el tipo de devolución es String.pero quiero fechar. –

+1

Puede 'analizar()' esa cadena para crear la instancia de fecha –

+0

Tan pronto como lo analiza, regresa al formato de zona horaria local. En mi caso, lo convierte de nuevo en IST. Cómo mantenerlo en GMT – user2531799

1

Me gusta este SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));?

Cuestiones relacionadas