Can I force Java to use the GMT / UTC + 0 time?

1

I am working with the APIs of Date and Time Java 8. In my code I am interested in taking the time GMT / UTC + 0 , but picks the one from the computer that is > GMT / UTC + 1 .

Can I force Java to do this without having to change the time on my computer?

    
asked by Macaroni 04.12.2018 в 12:45
source

4 answers

1

Finally I discovered it by myself. I added this line in VM arguments of run configurations and now I have GMT / UTC + 0 in my environment.

-Duser.timezone = UTC

    
answered by 04.12.2018 / 13:22
source
1

If you use Java 8 or higher, it would be enough to use

Instant.now()   // Captura el momento actual en UTC

If not, you can use these methods:

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

//Local time zone

SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

//Time en GMT
return dateFormatLocal.parse( dateFormatGmt.format(new Date()) );
    
answered by 04.12.2018 в 12:54
1

To take the time of a different time zone from your country, you must set the time zone of the place you need using the ZoneId class, then assign the ZoneId you set to the current time instance. at the beginning; for example:

ZoneId idZona = ZoneId.of("America/Los_Angeles");
LocalTime horaActual = LocalTime.now(idZona);
DateTimeFormatter formato = DateTimeFormatter.ofPattern("HH:mm:ss");
String horaFormateada = horaActual.format(formato);
System.out.println("La hora actual en Los Angeles es: " + horaFormateada);
    
answered by 04.12.2018 в 13:04
1

This code should return a Date with GMT + 0 as you want

private Date convertirAGmt(Date date){
    TimeZone tz = TimeZone.getDefault();
    Date ret = new Date( date.getTime() - tz.getRawOffset() );

    if (tz.inDaylightTime(ret)){
        Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );

        if (tz.inDaylightTime(dstDate)){
            ret = dstDate;
        }
     }
     return ret;
}

source: link

    
answered by 04.12.2018 в 13:00