When I create a new Date
object, it is initialized to the current time but in the local timezone. How can I get the current date and time in GMT?
34 Answers
tl;dr
Instant.now() // Capture the current moment in UTC.
Generate a String to represent that value:
Instant.now().toString()
2016-09-13T23:30:52.123Z
Details
As the correct answer by Jon Skeet stated, a java.util.Date object has no time zone†. But its toString
implementation applies the JVM’s default time zone when generating the String representation of that date-time value. Confusingly to the naïve programmer, a Date seems to have a time zone but does not.
The java.util.Date
, j.u.Calendar
, and java.text.SimpleDateFormat
classes bundled with Java are notoriously troublesome. Avoid them. Instead, use either of these competent date-time libraries:
- java.time.* package in Java 8
- Joda-Time
java.time (Java 8)
Java 8 brings an excellent new java.time.* package to supplant the old java.util.Date/Calendar classes.
Getting current time in UTC/GMT is a simple one-liner…
Instant instant = Instant.now();
That Instant
class is the basic building block in java.time, representing a moment on the timeline in UTC with a resolution of nanoseconds.
In Java 8, the current moment is captured with only up to milliseconds resolution. Java 9 brings a fresh implementation of Clock
captures the current moment in up to the full nanosecond capability of this class, depending on the ability of your host computer’s clock hardware.
It’s toString
method generates a String representation of its value using one specific ISO 8601 format. That format outputs zero, three, six or nine digits digits (milliseconds, microseconds, or nanoseconds) as necessary to represent the fraction-of-second.
If you want more flexible formatting, or other additional features, then apply an offset-from-UTC of zero, for UTC itself (ZoneOffset.UTC
constant) to get a OffsetDateTime
.
OffsetDateTime now = OffsetDateTime.now( ZoneOffset.UTC );
Dump to console…
System.out.println( "now.toString(): " + now );
When run…
now.toString(): 2014-01-21T23:42:03.522Z
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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 the java.time classes.
Using the Joda-Time 3rd-party open-source free-of-cost library, you can get the current date-time in just one line of code.
Joda-Time inspired the new java.time.* classes in Java 8, but has a different architecture. You may use Joda-Time in older versions of Java. Joda-Time continues to work in Java 8 and continues to be actively maintained (as of 2014). However, the Joda-Time team does advise migration to java.time.
System.out.println( "UTC/GMT date-time in ISO 8601 format: " + new org.joda.time.DateTime( org.joda.time.DateTimeZone.UTC ) );
More detailed example code (Joda-Time 2.3)…
org.joda.time.DateTime now = new org.joda.time.DateTime(); // Default time zone.
org.joda.time.DateTime zulu = now.toDateTime( org.joda.time.DateTimeZone.UTC );
Dump to console…
System.out.println( "Local time in ISO 8601 format: " + now );
System.out.println( "Same moment in UTC (Zulu): " + zulu );
When run…
Local time in ISO 8601 format: 2014-01-21T15:34:29.933-08:00
Same moment in UTC (Zulu): 2014-01-21T23:34:29.933Z
For more example code doing time zone work, see my answer to a similar question.
Time Zone
I recommend you always specify a time zone rather than relying implicitly on the JVM’s current default time zone (which can change at any moment!). Such reliance seems to be a common cause of confusion and bugs in date-time work.
When calling now()
pass the desired/expected time zone to be assigned. Use the DateTimeZone
class.
DateTimeZone zoneMontréal = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zoneMontréal );
That class holds a constant for UTC time zone.
DateTime now = DateTime.now( DateTimeZone.UTC );
If you truly want to use the JVM’s current default time zone, make an explicit call so your code is self-documenting.
DateTimeZone zoneDefault = DateTimeZone.getDefault();
ISO 8601
Read about ISO 8601 formats. Both java.time and Joda-Time use that standard’s sensible formats as their defaults for both parsing and generating strings.
† Actually, java.util.Date does have a time zone, buried deep under layers of source code. For most practical purposes, that time zone is ignored. So, as shorthand, we say java.util.Date has no time zone. Furthermore, that buried time zone is not the one used by Date’s toString
method; that method uses the JVM’s current default time zone. All the more reason to avoid this confusing class and stick with Joda-Time and java.time.
-
3
DateTime.now().toDateTime(DateTimeZone.UTC)
was what I was looking for! Thanks!– ManagarmJul 8, 2015 at 9:59 -
3@Managarm You can shorten that to:
DateTime nowUtc = DateTime.now ( DateTimeZone.UTC ) ;
Jul 8, 2015 at 16:29 -
How to get this with Pure Java 8
2014-01-21T15:34:29.933-08:00
in the example you usednew org.joda.time.DateTime()
Apr 22, 2019 at 12:13 -
1@GOXR3PLUS
ZonedDateTime.now( ZoneId.of( "America/Los_Angeles" ) ).truncatedTo( ChronoUnit.MILLIS ).toOffsetDateTime().toString()
We get the current moment for a specified time zone. Next, lop off any micros/nanos. Then we convert to having only a mere offset-from-UTC (number of hours-minutes-seconds) rather than a full-blown time zone (a history of past, present, and future changes in the offset used by the people of a particular region). Lastly, we generate text representing the value in thatOffsetDateTime
per the standard ISO 8601 format used by default in itstoString
method. Apr 26, 2019 at 4:15 -
1@RudraTiwari java.time uses the host OS’ to get the current time. If you cannot trust the local system’s clock, then make a network call to a time server. This topic has been addressed in several existing Questions and Answers on Stack Overflow, so search to learn more. Mar 21, 2022 at 11:55
java.util.Date
has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?
To be precise: the value within a java.util.Date
is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date
is the same around the world at any particular instant, regardless of local time zone.
I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString()
which also uses the local timezone, or a SimpleDateFormat
instance, which, by default, also uses local timezone.
If this isn't the problem, please post some sample code.
I would, however, recommend that you use Joda-Time anyway, which offers a much clearer API.
-
6Then that's probably a driver issue. You may need to set your connection to UTC, or something like that. I've seen problems like this before, but the problem is not in java.util.Date. Nov 21, 2008 at 14:07
-
15Behrang, according to stackoverflow.com/questions/4123534/…, the MySQL JDBC driver converts a given
java.util.Timestamp
(orjava.util.Date
) to the server time zone. Dec 7, 2010 at 21:02 -
6The
Date
documentation states : "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.". For instance in my machine or my android phone, when I initialize a new Date object is set to GMT not UTC. No downvote from me, maybe I understood it wrong. May 17, 2012 at 13:04 -
8@KanagaveluSugumar:
toString()
always uses the default time zone.date.getTime()
definitely returns milliseconds since the Unix epoch, in UTC. It's most accurate to say thatDate
itself doesn't have a time zone at all - it's just an instant in time, which could be regarded in multiple time zones. But when you create an instance, it doesn't depend on your time zone. Dec 28, 2012 at 12:33 -
6@Jemenake: Actually it didn't happen when it was midnight in Greenwich, because the UK was on UTC+1 at the time. Just one of the odd bits of history. But I take your point - it's better to say "new Date().getTime() returns the milliseconds since the Unix epoch, which was midnight at the start of January 1st 1970, UTC". So the UTC is part of pinning down the epoch to a particular instant in time, not part of the result. May 1, 2013 at 15:05
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
//Local time zone
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
//Time in GMT
return dateFormatLocal.parse( dateFormatGmt.format(new Date()) );
-
11Why do you parse with dateFormatLocal after using dateFormatGmt format... does not make sense by reading it. I am sure it works, but just wondering?– MindWireJun 15, 2012 at 21:20
-
2setTimeZone did it (I guess you can also use getTimeZone("UTC") same thing as GMT?) Feb 6, 2013 at 0:05
-
6but the time is dependent on device set time. If user has set wrong time on his device then you will get wrong UTC .correct me if am wrong Aug 21, 2013 at 16:48
-
@BasavarajHampali but in todays world most of the devices are connected to the internet which corrects incorrect time Oct 30, 2013 at 15:18
-
3There is no time difference between Coordinated Universal Time (UTC) and Greenwich Mean Time (GMT)– slottDec 16, 2014 at 10:11
This definitely returns UTC time: as String and Date objects !
static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static Date getUTCdatetimeAsDate() {
// note: doesn't check for null
return stringDateToDate(getUTCdatetimeAsString());
}
public static String getUTCdatetimeAsString() {
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
return utcTime;
}
public static Date stringDateToDate(String StrDate) {
Date dateToReturn = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);
try {
dateToReturn = (Date)dateFormat.parse(StrDate);
}
catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn;
}
-
In my answer I forgot to show how DATEFORMAT is defined:
static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ss";
Jul 26, 2011 at 19:39 -
21Please avoid starting method names with uppercase in Java. See the Java coding conventions for method names. May 2, 2015 at 14:42
-
2As am redirected to this answer, Calling
new Date()
will never return the correct UTC time, if the device time is wrong. Mar 2, 2017 at 8:55 -
-
One thing to note. Any solution that needs to get a Date or Timestamp in UTC, it looks like the key is to not re-use the SimpleDateFormat, but rather use one to get UTC into a string, then create another UTC when converting the string to either a Date or Timestamp Object. I noticed that if you try to reuse the same SimpleDateFormat then the resulting Date/Timestamp Object will revert to the local timezone instead of UTC. Feb 26, 2019 at 4:28
Calendar c = Calendar.getInstance();
System.out.println("current: "+c.getTime());
TimeZone z = c.getTimeZone();
int offset = z.getRawOffset();
if(z.inDaylightTime(new Date())){
offset = offset + z.getDSTSavings();
}
int offsetHrs = offset / 1000 / 60 / 60;
int offsetMins = offset / 1000 / 60 % 60;
System.out.println("offset: " + offsetHrs);
System.out.println("offset: " + offsetMins);
c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
c.add(Calendar.MINUTE, (-offsetMins));
System.out.println("GMT Time: "+c.getTime());
Actually not time, but it's representation could be changed.
SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(f.format(new Date()));
Time is the same in any point of the Earth, but our perception of time could be different depending on location.
-
Yep, nice and clean solution. It just worries me, if its ineffective to create a new Date object instead of just getting Calendar instance?– BeemoOct 6, 2015 at 14:53
-
It will be optimized by JVM and HotSpot will execute the most effective x86 code possible– AnthonyOct 7, 2015 at 4:49
-
-
A bit clarification,
UTC
is a time standard,rather than a timezone. Actually "GMT" is the timezone which in same time as UTC practically. Sep 13, 2021 at 3:52
This works for getting UTC milliseconds in Android.
Calendar c = Calendar.getInstance();
int utcOffset = c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET);
Long utcMilliseconds = c.getTimeInMillis() + utcOffset;
-
7
-
c.add(Calendar.MILLISECOND, (-utcOffset))
to get Calendar with utc timezone Nov 19, 2015 at 14:18 -
Calendar.getInstance().apply { timeInMillis -= get(Calendar.ZONE_OFFSET) + get(Calendar.DST_OFFSET) }
– JovinNov 7, 2022 at 11:58
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); Then all operations performed using the aGMTCalendar object will be done with the GMT time zone and will not have the daylight savings time or fixed offsets applied
Wrong!
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
aGMTCalendar.getTime(); //or getTimeInMillis()
and
Calendar aNotGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT-2"));aNotGMTCalendar.getTime();
will return the same time. Idem for
new Date(); //it's not GMT.
This code prints the current time UTC.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Test
{
public static void main(final String[] args) throws ParseException
{
final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(f.format(new Date()));
}
}
Result
2013-10-26 14:37:48 UTC
Here is what seems to be incorrect in Jon Skeet's answer. He said:
java.util.Date
is always in UTC. What makes you think it's in local time? I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly usingDate.toString()
which also uses the local timezone.
However, the code:
System.out.println(new java.util.Date().getHours() + " hours");
gives the local hours, not GMT (UTC hours), using no Calendar
and no SimpleDateFormat
at all.
That is why is seems something is incorrect.
Putting together the responses, the code:
System.out.println(Calendar.getInstance(TimeZone.getTimeZone("GMT"))
.get(Calendar.HOUR_OF_DAY) + " Hours");
shows the GMT hours instead of the local hours -- note that getTime.getHours()
is missing because that would create a Date()
object, which theoretically stores the date in GMT, but gives back the hours in the local time zone.
-
9I hadn't seen this answer before, but if you read the documentation for the deprecated
Date.getHours()
method, it makes it very clear: "The returned value is a number (0 through 23) representing the hour within the day that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone." (Emphasis mine.) It's thegetHours()
method which interprets the value within the local time zone - it's not part of the state of theDate
object itself. May 11, 2013 at 13:57 -
3As Jon Skeet correctly stated, a java.util.Date object has no time zone. But confusingly, the methods
toString
andgetHours
apply the default time zone to their output. So, naïve programmers are easily fooled as it seems a Date has a time zone but in fact does not. Jan 22, 2014 at 1:14 -
The
getHours()
method has been deprecated for more than 25 years exactly because it works unreliably across time zones. So what you are showing is not that Jon Skeet was wrong (which he wasn’t), but that there was good reason for the deprecation.– Ole V.V.Mar 26, 2022 at 12:19
If you want a Date object with fields adjusted for UTC you can do it like this with Joda Time:
import org.joda.time.DateTimeZone;
import java.util.Date;
...
Date local = new Date();
System.out.println("Local: " + local);
DateTimeZone zone = DateTimeZone.getDefault();
long utc = zone.convertLocalToUTC(local.getTime(), false);
System.out.println("UTC: " + new Date(utc));
-
1You are working too hard. Joda-Time can do this in a single line of code. See my own answer on this question. Call the
.toDateTime
method and pass the constant for the UTC time zone. Nov 8, 2013 at 11:26 -
1
You can use:
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Then all operations performed using the aGMTCalendar object will be done with the GMT time zone and will not have the daylight savings time or fixed offsets applied. I think the previous poster is correct that the Date() object always returns a GMT it's not until you go to do something with the date object that it gets converted to the local time zone.
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(date));
-
Please add some explanation to your answer, how is it different from so many other answers?– akjoshiDec 4, 2012 at 7:18
-
Here is my implementation of toUTC:
public static Date toUTC(Date date){
long datems = date.getTime();
long timezoneoffset = TimeZone.getDefault().getOffset(datems);
datems -= timezoneoffset;
return new Date(datems);
}
There's probably several ways to improve it, but it works for me.
You can directly use this
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(new Date())+"");
Here an other suggestion to get a GMT Timestamp object:
import java.sql.Timestamp;
import java.util.Calendar;
...
private static Timestamp getGMT() {
Calendar cal = Calendar.getInstance();
return new Timestamp(cal.getTimeInMillis()
-cal.get(Calendar.ZONE_OFFSET)
-cal.get(Calendar.DST_OFFSET));
}
Here is another way to get GMT time in String format
String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z" ;
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateTimeString = sdf.format(new Date());
With:
Calendar cal = Calendar.getInstance();
Then cal
have the current date and time.
You also could get the current Date and Time for timezone with:
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT-2"));
You could ask cal.get(Calendar.DATE);
or other Calendar constant about others details.
Date and Timestamp are deprecated in Java. Calendar class it isn't.
-
6Certain methods and constructors of Date and Timestamp are deprecated, but the classes themselves are not. Nov 21, 2008 at 13:19
Sample code to render system time in a specific time zone and a specific format.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class TimZoneTest {
public static void main (String[] args){
//<GMT><+/-><hour>:<minutes>
// Any screw up in this format, timezone defaults to GMT QUIETLY. So test your format a few times.
System.out.println(my_time_in("GMT-5:00", "MM/dd/yyyy HH:mm:ss") );
System.out.println(my_time_in("GMT+5:30", "'at' HH:mm a z 'on' MM/dd/yyyy"));
System.out.println("---------------------------------------------");
// Alternate format
System.out.println(my_time_in("America/Los_Angeles", "'at' HH:mm a z 'on' MM/dd/yyyy") );
System.out.println(my_time_in("America/Buenos_Aires", "'at' HH:mm a z 'on' MM/dd/yyyy") );
}
public static String my_time_in(String target_time_zone, String format){
TimeZone tz = TimeZone.getTimeZone(target_time_zone);
Date date = Calendar.getInstance().getTime();
SimpleDateFormat date_format_gmt = new SimpleDateFormat(format);
date_format_gmt.setTimeZone(tz);
return date_format_gmt.format(date);
}
}
Output
10/08/2011 21:07:21
at 07:37 AM GMT+05:30 on 10/09/2011
at 19:07 PM PDT on 10/08/2011
at 23:07 PM ART on 10/08/2011
Just to make this simpler, to create a Date
in UTC
you can use Calendar
:
Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Which will construct a new instance for Calendar
using the "UTC" TimeZone
.
If you need a Date
object from that calendar you could just use getTime()
.
-
7Calling getTime() on this causes it to lose the time zone information and return local time. Sep 19, 2013 at 1:10
Converting Current DateTime in UTC:
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTimeZone dateTimeZone = DateTimeZone.getDefault(); //Default Time Zone
DateTime currDateTime = new DateTime(); //Current DateTime
long utcTime = dateTimeZone.convertLocalToUTC(currDateTime .getMillis(), false);
String currTime = formatter.print(utcTime); //UTC time converted to string from long in format of formatter
currDateTime = formatter.parseDateTime(currTime); //Converted to DateTime in UTC
-
1You are doing too much work here. (a) The formatter patter you define is already built into a DateTime by default; just call
toString
on a DateTime to get that ISO 8601 string pattern. (b) Way too much code to convert between time zones. Simply call "toDateTime" and pass a time zone object. Like this:myDateTime.toDateTime( DateTimeZone.UTC )
. For a specific time zone, instantiate and pass a time zone object based on a proper name, callmyDateTime.toDateTime( DateTimeZone.forID( "Asia/Tehran" ) )
. Jan 23, 2014 at 21:48
public static void main(String args[]){
LocalDate date=LocalDate.now();
System.out.println("Current date = "+date);
}
This worked for me, returns the timestamp in GMT!
Date currDate;
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
long currTime = 0;
try {
currDate = dateFormatLocal.parse( dateFormatGmt.format(new Date()) );
currTime = currDate.getTime();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The Simple Function that you can use:
Edit: this version uses the modern java.time classes.
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("dd-MM-uuuu HH:mm:ss z");
public static String getUtcDateTime() {
return ZonedDateTime.now(ZoneId.of("Etc/UTC")).format(FORMATTER);
}
Return value from the method:
26-03-2022 17:38:55 UTC
Original function:
public String getUTC_DateTime() {
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));//gmt
return dateTimeFormat.format(new Date());
}
return of above function:
26-03-2022 08:07:21 UTC
-
Thanks, @OleV.V. making it clear and more updated, for me and everyone. In short your comment also teach me well. keep it up.– AmmarMar 26, 2022 at 15:10
To put it simple. A calendar object stores information about time zone but when you perform cal.getTime() then the timezone information will be lost. So for Timezone conversions I will advice to use DateFormat classes...
this is my implementation:
public static String GetCurrentTimeStamp()
{
Calendar cal=Calendar.getInstance();
long offset = cal.getTimeZone().getOffset(System.currentTimeMillis());//if you want in UTC else remove it .
return new java.sql.Timestamp(System.currentTimeMillis()+offset).toString();
}
Use this Class to get ever the right UTC Time from a Online NTP Server:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class NTP_UTC_Time
{
private static final String TAG = "SntpClient";
private static final int RECEIVE_TIME_OFFSET = 32;
private static final int TRANSMIT_TIME_OFFSET = 40;
private static final int NTP_PACKET_SIZE = 48;
private static final int NTP_PORT = 123;
private static final int NTP_MODE_CLIENT = 3;
private static final int NTP_VERSION = 3;
// Number of seconds between Jan 1, 1900 and Jan 1, 1970
// 70 years plus 17 leap days
private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
private long mNtpTime;
public boolean requestTime(String host, int timeout) {
try {
DatagramSocket socket = new DatagramSocket();
socket.setSoTimeout(timeout);
InetAddress address = InetAddress.getByName(host);
byte[] buffer = new byte[NTP_PACKET_SIZE];
DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);
buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
socket.send(request);
// read the response
DatagramPacket response = new DatagramPacket(buffer, buffer.length);
socket.receive(response);
socket.close();
mNtpTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
} catch (Exception e) {
// if (Config.LOGD) Log.d(TAG, "request time failed: " + e);
return false;
}
return true;
}
public long getNtpTime() {
return mNtpTime;
}
/**
* Reads an unsigned 32 bit big endian number from the given offset in the buffer.
*/
private long read32(byte[] buffer, int offset) {
byte b0 = buffer[offset];
byte b1 = buffer[offset+1];
byte b2 = buffer[offset+2];
byte b3 = buffer[offset+3];
// convert signed bytes to unsigned values
int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
}
/**
* Reads the NTP time stamp at the given offset in the buffer and returns
* it as a system time (milliseconds since January 1, 1970).
*/
private long readTimeStamp(byte[] buffer, int offset) {
long seconds = read32(buffer, offset);
long fraction = read32(buffer, offset + 4);
return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
}
/**
* Writes 0 as NTP starttime stamp in the buffer. --> Then NTP returns Time OFFSET since 1900
*/
private void writeTimeStamp(byte[] buffer, int offset) {
int ofs = offset++;
for (int i=ofs;i<(ofs+8);i++)
buffer[i] = (byte)(0);
}
}
And use it with:
long now = 0;
NTP_UTC_Time client = new NTP_UTC_Time();
if (client.requestTime("pool.ntp.org", 2000)) {
now = client.getNtpTime();
}
If you need UTC Time "now" as DateTimeString use function:
private String get_UTC_Datetime_from_timestamp(long timeStamp){
try{
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
int tzt = tz.getOffset(System.currentTimeMillis());
timeStamp -= tzt;
// DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
DateFormat sdf = new SimpleDateFormat();
Date netDate = (new Date(timeStamp));
return sdf.format(netDate);
}
catch(Exception ex){
return "";
}
}
and use it with:
String UTC_DateTime = get_UTC_Datetime_from_timestamp(now);
-
In single line <br/> <pre> <code>Calendar utcTime = Calendar.getInstance().add(Calendar.MILLISECOND, -time.getTimeZone().getOffset(time.getTimeInMillis()));</pre> </code>– HarunNov 28, 2013 at 9:24
-
2Yes, but this calls the local Device Time, which could changed manualy from the user to a false DateTime– IngoDec 3, 2013 at 14:59
If you want to avoid parsing the date and just want a timestamp in GMT, you could use:
final Date gmt = new Timestamp(System.currentTimeMillis()
- Calendar.getInstance().getTimeZone()
.getOffset(System.currentTimeMillis()));
public class CurrentUtcDate
{
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC Time is: " + dateFormat.format(date));
}
}
Output:
UTC Time is: 22-01-2018 13:14:35
You can change the date format as needed.
-
2Please don’t teach the young ones to use the long outdated and notoriously troublesome
SimpleDateFormat
. Today we have so much better injava.time
, the modern Java date and time API. Also what are you providing that isn’t already in the answers by Dan, Antonio and others?– Ole V.V.Jul 4, 2018 at 5:11 -
2(a) How does this Answer add value over the dozens of existing Answers? (b) The troublesome classes used here were supplanted years ago by the modern java.time classes. Suggesting their use in 2018 is poor advice. Jul 4, 2018 at 7:27
-
I am sorry, But that time I did't use time API. Anyway I agree with your point and will try my best to post latest better solutions. Jun 5, 2021 at 14:16
Current date in the UTC
Instant.now().toString().replaceAll("T.*", "");
-
1
Date
doesn’t hold a time zone, so "but in the local timezone” is not correct (or inaccurate at best). See All about java.util.Date.