Trying to get Universal Time in java seems to be so difficult. Something like this in C#
DateTime.Now.ToUniversalTime()
seems to be something so difficult. I have code that subtracts a current utc time from a earlier date that is also utc to find the difference in time. But I can't seem to see how to get the current utc time. this is my current code
Date date = new Date();
long difference = date.getTime() - s.getTime();
s is already in utc time because it comes from a source that is passing me the utc time
Give this a try:
Date utcDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
Best,
Loddi
tl;dr
Current moment in UTC:
Instant.now()
Elapsed time:
Instant then = … ;
Instant now = Instant.now();
Duration duration = Duration.between( then , now ); // For days-hours-minutes-seconds scale.
Render as a count of milliseconds.
long millis = duration.toMillis(); // Possible data-loss in truncating nanoseconds to milliseconds.
java.time
The modern approach to date-time handling in Java is the java.time classes.
Instant
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now(); // Current moment in UTC.
The Duration
class represents a span of time unattached to the timeline. You can feed in a pair of Instant
objects to calculate the number of days, hours, minutes, seconds, and nanoseconds in between.
Duration duration = Duration.between( thisInstant , thatInstant );
Call toString
to generate a string in standard ISO 8601 format of PnYnMnDTnHnMnS
where P
marks the beginning and T
separates any years-months-days from the hours-minutes-seconds. For example, an hour and a half is PT1H30M
.
You can get the total number of milliseconds in this duration. But beware of possible data-loss. The Instant
and Duration
classes work in a resolution of nanoseconds, much finer than milliseconds. So extracting milliseconds will truncate any fraction of a second beyond the milliseconds. In other words, rather than having a split second with a decimal representation of up to nine digits, you will have only up to three digits.
long millis = duration.toMillis(); // Possible data-loss in truncating nanoseconds to milliseconds.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Joda-Time
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to java.time. Leaving this section intact for history.
Using the Joda-Time 2.4 library.
DateTime nowUtc = DateTime.now( DateTimeZone.UTC );
Best to avoid java.util.Date and .Calendar as they are notoriously troublesome. But if you must, you can convert.
Date date = nowUtc.toDate();
As for getting a difference between date-time values, search StackOverflow for hundreds of answers. Joda-Time offers 3 classes for representing a span of time: Interval, Period, and Duration.
You can use follwing method to find UTC time:
Calender c= Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Then you can get month,day ,time ,year ant from the calender object..
ex: c.get(Calender.YEAR)
Hope this will help you..
Date is in UTC. There's no time zone attached to Date.
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#getTime()
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
What makes you think it's in local time?
Edit: The documentation does say this, so maybe that's the problem:
Although the Date class is intended to reflect coordinated universal
time (UTC), it may not do so exactly, depending on the host
environment of the Java Virtual Machine.
It looks like this might be a good solution:
Calendar c = Calendar.getInstance();
int utcOffset = c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET);
Long utcMilliseconds = c.getTimeInMillis() + utcOffset;
Hmm, no one mentioned System.currentTimeMillis()
so i will :) This will return the number of millis since the Unix epoch. This will always be in UTC (e.g. if you call it at the same time in London and in Athens you will get the same values - if the times are set correctly on those devices the timezone shouldn't matter). If you want to obtain a Calendar instance from a number of millis you can just do something like:
Calendar cal = GregorianCalendar.getInstance();
cal.setTimeInMillis(yourMillis);