Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current date and time of your timezone in Java?

I have my app hosted in a London Server. I am in Madrid, Spain. So the timezone is -2 hours.

How can I obtain the current date / time with my time zone.

Date curr_date = new Date(System.currentTimeMillis());

e.g.

Date curr_date = new Date(System.currentTimeMillis("MAD_TIMEZONE"));

With Joda-Time

DateTimeZone zone = DateTimeZone.forID("Europe/Madrid");
DateTime dt = new DateTime(zone);
int day = dt.getDayOfMonth();
int year = dt.getYear();
int month = dt.getMonthOfYear();
int hours = dt.getHourOfDay();
int minutes = dt.getMinuteOfHour();
like image 785
Sergio del Amo Avatar asked Aug 20 '09 10:08

Sergio del Amo


People also ask

How can I get the current date and time in UTC or GMT in Java?

SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); f. setTimeZone(TimeZone. getTimeZone("UTC")); System. out.

Can we get TimeZone from date Java?

Date does not have a time zone associated with it. Its toString() method may make it appear to have a time zone, but it doesn't. The time zone provided by toString() is the system default time zone. A Calendar does have a time zone associated with it.


2 Answers

Date is always UTC-based... or time-zone neutral, depending on how you want to view it. A Date only represents a point in time; it is independent of time zone, just a number of milliseconds since the Unix epoch. There's no notion of a "local instance of Date." Use Date in conjunction with Calendar and/or TimeZone.getDefault() to use a "local" time zone. Use TimeZone.getTimeZone("Europe/Madrid") to get the Madrid time zone.

... or use Joda Time, which tends to make the whole thing clearer, IMO. In Joda Time you'd use a DateTime value, which is an instant in time in a particular calendar system and time zone.

In Java 8 you'd use java.time.ZonedDateTime, which is the Java 8 equivalent of Joda Time's DateTime.

like image 91
Jon Skeet Avatar answered Oct 23 '22 04:10

Jon Skeet


As Jon Skeet already said, java.util.Date does not have a time zone. A Date object represents a number of milliseconds since January 1, 1970, 12:00 AM, UTC. It does not contain time zone information.

When you format a Date object into a string, for example by using SimpleDateFormat, then you can set the time zone on the DateFormat object to let it know in which time zone you want to display the date and time:

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

System.out.println("Date and time in Madrid: " + df.format(date));

If you want the local time zone of the computer that your program is running on, use:

df.setTimeZone(TimeZone.getDefault());
like image 41
Jesper Avatar answered Oct 23 '22 05:10

Jesper