TimeZone Task in Java

I'm trying to instantiate a GregorianCalendar with TimeZone GMT, but whenever I call the getTime () method, it gives me time in the local TimeZone. Here is my code:

Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
System.out.println(cal.getTime());

The result I get is the following:

Sat Nov 28 19:55:49 PKT 2009

Please, help!

+3
source share
2 answers

I'm not sure if this answers your question, but this is one way to get "now" in GMT.

import java.text.*
import java.util.* 

Calendar cal = new GregorianCalendar();
Date date = cal.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(formatter.format(date));

See Javadoc on SimpleDateFormat for different templates. In addition, you can consider Joda Time as it is far superior to dates and times.

+9
source

GregorianCalendar, Date, / toString println.

, DateFormat - SimpleDateFormat, , , .

, getInstance... factory DateFormat.

setTimeZone DateFormat ( SimpleDateFormat, ).

+6

Source: https://habr.com/ru/post/1724169/


All Articles