75

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();
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Sergio del Amo
  • 76,835
  • 68
  • 152
  • 179
  • possible duplicate of [How can I get the current date and time in UTC or GMT in Java?](http://stackoverflow.com/questions/308683/how-can-i-get-the-current-date-and-time-in-utc-or-gmt-in-java) – Piskvor left the building Dec 20 '10 at 12:23
  • For example code using Joda-Time to translate between time zones, see [my answer](http://stackoverflow.com/a/19378311/642706) on the question [Java Convert GMT/UTC to Local time doesn't work as expected](http://stackoverflow.com/questions/19375357/java-convert-gmt-utc-to-local-time-doesnt-work-as-expected/19378311#19378311) – Basil Bourque Oct 28 '13 at 10:11

14 Answers14

103

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 5
    `Date currentDate = Calendar.getInstance(TimeZone.getDefault()).getTime()` – user3132194 Jun 24 '16 at 10:59
  • 2
    @user3132194: And what benefit do you think that will have over `new Date()`? – Jon Skeet Jun 24 '16 at 14:08
  • It is just a template for copy-paste, based on your answer. You said that `Date is always UTC-based`. I need local time. – user3132194 Jun 29 '16 at 11:07
  • 2
    @user3132194: That's a *terrible* template to copy and paste. There's no benefit over `new Date()`. If you want a local time, you shouldn't use `Date`. If you think your code does something useful over `new Date()`, I suspect you've misunderstood. – Jon Skeet Jun 29 '16 at 11:09
  • You are right `new Date()`, `java.util.Calendar.getInstance(java.util.TimeZone.getDefault()).getTime()` and even `java.util.Calendar.getInstance(java.util.TimeZone.getTimeZone("Europe/Madrid")).getTime()` works the same. But then unfortunately your answer is wrong. Or could you show me a good template? It seems only Jesper answer is correct. – user3132194 Jul 01 '16 at 05:57
  • @user3132194: No, my answer is *not* wrong. I've suggested either using Joda Time (and would now say `java.time`) or `Calendar`. Both of those are working options. In what way is my answer "wrong"? Will edit it to clarify it, but just claiming it's wrong is inappropriate, IMO. – Jon Skeet Jul 01 '16 at 06:01
  • Sorry, I'll get my vote back, just because there is the better and clearer answer. Thanks for this lesson though. – user3132194 Jul 01 '16 at 06:18
71

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());
Jesper
  • 202,709
  • 46
  • 318
  • 350
  • It seems to be in though: https://mkyong.com/java8/java-display-all-zoneid-and-its-utc-offset/ – mjs Aug 15 '20 at 13:38
  • @mmm What I wrote is that specifically a `java.util.Date` object does not contain timezone information. That does not mean that Java in general doesn't know about time zones - indeed it does, as you've discovered. The example you linked to just prints the time zones that Java knows, this has nothing to do specifically with class `java.util.Date`. The example doesn't even use that class at all. – Jesper Aug 16 '20 at 01:04
  • I was just saying that TimeZone.getTimeZone("") takes a String, and there was no evidence prior to the link that the passed string you supplied is valid as Java df.setTimezone will not cause an error according to documentation. – mjs Aug 18 '20 at 17:52
16

using Calendar is simple:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Madrid"));
Date currentDate = calendar.getTime();
dfa
  • 114,442
  • 31
  • 189
  • 228
  • 2
    Won't "GMT-2" give the "always GMT-2" zone, which won't include daylight savings? – Jon Skeet Aug 20 '09 at 10:59
  • you're right, I'm looking for a timezone sheet for handling daylight savings (I was not sure about -2) – dfa Aug 20 '09 at 11:02
  • Because stackoverflow is not Google. So answering trivial questions provoke people asking more stupid questions instead of reading documentation and googling. – stepancheg Aug 20 '09 at 11:11
  • 11
    please read the stackoverflow FAQ at http://stackoverflow.com/faq: "No question is too trivial or too "newbie". Oh yes, and it should be about programming." – dfa Aug 20 '09 at 11:19
  • FAQ is wrong. There must be an item: "Spend 5 minutes googling and reading documentation before asking". Of course newbie questions that are not answerable by Google are OK. – stepancheg Aug 20 '09 at 11:52
  • 16
    The FAQ is correct. If someone Googles **any** programming question, we'd like Stack Overflow to be the top search result (or very near to it). This means that even the most trivial question, if it does not already exist on SO, is fair game. – Bill the Lizard Aug 20 '09 at 13:16
  • 5
    Even if you set a time zone for a calendar instance it won't be considered for the `getTime()` method. From its javadocs: `Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").` – Danny Lo Dec 15 '15 at 11:39
  • `Calendar.getInstance(TimeZone.getTimeZone("Europe/Madrid")).getTime()` returns a Date in UTC. – user3132194 Jul 01 '16 at 06:21
  • @dfa I have tried your code, I'm still getting local timezone of server (IST). – Nitin Dhomse Aug 07 '17 at 09:12
  • I passed this code verbatim into `new SimpleDateFormat("...").format()` and `getTime()` always returns the UTC representation of the date. – NobleUplift Sep 06 '18 at 14:31
  • The Date object still represents only an instance of time, not a local timezone representation of it. Use the `get(int)` method of the Calendar object to get local time values. – fishinear Jan 06 '21 at 17:16
15

With the java.time classes built into Java 8 and later:

public static void main(String[] args) {
        LocalDateTime localNow = LocalDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
        System.out.println(localNow);
        // Prints current time of given zone without zone information : 2016-04-28T15:41:17.611
        ZonedDateTime zoneNow = ZonedDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
        System.out.println(zoneNow);
        // Prints current time of given zone with zone information : 2016-04-28T15:41:17.627+02:00[Europe/Madrid]
    }
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Zeeshan
  • 11,851
  • 21
  • 73
  • 98
2

You would use JodaTime for that. Java.util.Date is very limited regarding TimeZone.

Joshua Partogi
  • 16,167
  • 14
  • 53
  • 75
  • java.util.Date is deliberately divorced from TimeZone. For simple "what is the time in a particular time zone" java.util.* isn't too bad... but I agree that Joda Time is simply a better API in general. – Jon Skeet Aug 20 '09 at 10:55
2

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API: If you want to get just date and time (and not the timezone information), you can use LocalDateTime.#now(ZoneId).

The non-parametrized overloaded, LocalDateTime.#now returns the current Date-Time using the JVM's timezone. It is equivalent to using LocalDateTime.now(ZoneId.systemDefault()).

Demo:

import java.time.LocalDateTime;
import java.time.ZoneId;

public class Main {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now(ZoneId.of("Europe/Madrid"));
        System.out.println(now);
    }
}

Output from a sample run:

2021-07-25T15:54:31.574424

ONLINE DEMO

If you want to get the date and time along with the timezone information, you can use ZonedDateTime.#now(ZoneId). It's non-parametrized variant behave in the same manner as described above.

Demo:

import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Madrid"));
        System.out.println(now);
    }
}

Output from a sample run:

2021-07-25T16:08:54.741773+02:00[Europe/Madrid]

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
2

Check this may be helpful. Works fine for me. Code also covered daylight savings

    TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
    Calendar cal = Calendar.getInstance();      
    // If needed in hours rather than milliseconds
    int LocalOffSethrs = (int) ((cal.getTimeZone().getRawOffset()) *(2.77777778 /10000000));        
    int ChinaOffSethrs = (int) ((tz.getRawOffset()) *(2.77777778 /10000000));       
    int dts = cal.getTimeZone().getDSTSavings();
    System.out.println("Local Time Zone : " + cal.getTimeZone().getDisplayName());
    System.out.println("Local Day Light Time Saving : " + dts);
    System.out.println("China Time : " + tz.getRawOffset());
    System.out.println("Local Offset Time from GMT: " + LocalOffSethrs);
    System.out.println("China Offset Time from GMT: " + ChinaOffSethrs);    
    // Adjust to GMT
    cal.add(Calendar.MILLISECOND,-(cal.getTimeZone().getRawOffset()));  
    // Adjust to Daylight Savings
    cal.add(Calendar.MILLISECOND, - cal.getTimeZone().getDSTSavings());
    // Adjust to Offset
    cal.add(Calendar.MILLISECOND, tz.getRawOffset());       
    Date dt = new Date(cal.getTimeInMillis());              
    System.out.println("After adjusting offset Acctual China Time :" + dt); 
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
Subhamay
  • 197
  • 1
  • 5
  • Nice example, but trying it with my timezone (EST) does not return the right value. Working with RawOffset does not consider DST. So i end up with 1hr earlier. – Cygnusx1 Nov 02 '12 at 14:13
  • "Converting" to another timezone by adding/subtracting time durations will really get you into loads of problems. To convert to another timezone, you should really create a new Calendar object for the new timezone, set the Date for that, and then use the `get(int)` method to get time values for that timezone. – fishinear Jan 06 '21 at 17:28
1

I couldn't get it to work using Calendar. You have to use DateFormat

//Wednesday, July 20, 2011 3:54:44 PM PDT
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateTimeString = df.format(new Date());

//Wednesday, July 20, 2011
df = DateFormat.getDateInstance(DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateString = df.format(new Date());

//3:54:44 PM PDT
df = DateFormat.getTimeInstance(DateFormat.FULL);
df.setTimeZone(Timezone.getTimeZone("PST"));
final String timeString = df.format(new Date());
wjin
  • 954
  • 1
  • 8
  • 13
  • DateFormat is a good approach if you need the date/time as a String. If you need the values as numbers, then use Calendar. – fishinear Jan 06 '21 at 17:30
1

You can try ZonedDateTime.now() . You can find it in package java.time

import java.time.ZonedDateTime;

public class Temp {
public static void main(String args[]) {
    System.out.println(ZonedDateTime.now(ZoneId.of("Europe/Madrid")));
}

}

Output (I'm based in kolkata,India):

2021-09-17T14:46:14.341+02:00[Europe/Madrid]
Bablu
  • 161
  • 7
0

To get date and time of your zone.

Date date = new Date();
DateFormat df = new SimpleDateFormat("MM/dd/YYYY HH:mm a");
df.setTimeZone(TimeZone.getDefault());
df.format(date);
Umer Khalid
  • 330
  • 2
  • 16
0

To get the date to a variable .

public static  String  getCurrentDate(){
    final ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
    String Temporal= DateTimeFormatter.ofPattern("yyyy-MM-dd").format(now);
    String today= LocalDate.now().format(DateTimeFormatter.ofPattern(Temporal));
    return today;
}
Sameera De Silva
  • 1,722
  • 1
  • 22
  • 41
-1

Here are some steps for finding Time for your zone:

Date now = new Date();

 DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");  
 df.setTimeZone(TimeZone.getTimeZone("Europe/London"));  

 System.out.println("timeZone.......-->>>>>>"+df.format(now));  
shan
  • 186
  • 2
  • 14
  • 5
    Not only does this answer duplicate [one posted years ago](http://stackoverflow.com/a/1305454/642706), it lacks any useful explanation. I suggest withdrawing this answer. – Basil Bourque Jul 16 '14 at 18:56
-1

Date in 24 hrs format

Output:14/02/2020 19:56:49 PM

 Date date = new Date();
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aa");
 dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
 System.out.println("date is: "+dateFormat.format(date));

Date in 12 hrs format

Output:14/02/2020 07:57:11 PM

 Date date = new Date();`enter code here`
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
 dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
 System.out.println("date is: "+dateFormat.format(date));
Siva
  • 113
  • 4
  • 13
-2
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateTimeString = df.format(new Date());
stema
  • 90,351
  • 20
  • 107
  • 135
shamim
  • 11