System.currentTimeMillis() not displaying time in UTC , instead displaying current timezone time

I have a requirement of getting UTC time , hence in many places iam using below code for calcualting utc time.

System.currentTimeMillis() ;

Iam in IST - (GMT+5:30) , System.currentTimeMillis() - should display UTC time (IST-5:30) , instead it is taking current time (GMT+5:30). I donot want to use the Apache of joda date and time api. i want to use the Java api itslef. Help me in resolve my issue.

Jon Skeet
people
quotationmark

System.currentTimeMillis() just returns a long - that's not in any sort of date format.

If you're actually using:

Date date = new Date(System.currentTimeMillis());
System.out.println(date);

then you're just seeing the result of Date.toString(), which always uses the system default time zone.

Use DateFormat (e.g. SimpleDateFormat) to specify the calendar system (typically Gregorian), time zone and format you want to use. For example:

Date date = ...;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",
                                         Locale.US);
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

String result = format.format(date);

As an aside, I'd strongly recommend abstracting the idea of "getting the current time" into an interface which you implement in one case using System.currentTimeMillis() (or equivalently, just new Date()) but implement for testing purposes with a value you can set and update at will. Then inject this "clock" interface into anything which needs to access the current date/time. It makes it much easier to test time-based components.

(I'd also strongly recommend using Joda Time or the java.time package from Java 8 if you possibly can. I know you've said you don't want to, but I suspect that's because you haven't spent as much time swearing at java.util.Date and java.util.Calendar as some of us. Both of those alternatives will lead to much cleaner code which is much easier to read and reason about. If you're trying to avoid a one-time hit of getting Joda Time into your build process, weigh that against the amount of time you're likely to spend maintaining your code. Or just update to Java 8... Java 7 will be out of free-update support soon anyway...)

people

See more on this question at Stackoverflow