How to get the current date and time of your timezone in Java?
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
.
How can I get the current date and time in UTC or GMT in Java?
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.
How to get the current date/time in Java
It depends on what form of date / time you want:
If you want the date / time as a single numeric value, then
System.currentTimeMillis()
gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Javalong
). This value is a delta from a UTC time-point, and is independent of the local time-zone1.If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:
new Date()
gives you aDate
object initialized with the current date / time. The problem is that theDate
API methods are mostly flawed ... and deprecated.Calendar.getInstance()
gives you aCalendar
object initialized with the current date / time, using the defaultLocale
andTimeZone
. Other overloads allow you to use a specificLocale
and/orTimeZone
. Calendar works ... but the APIs are still cumbersome.new org.joda.time.DateTime()
gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. https://stackoverflow.com/questions/6280829.)in Java 8, calling
java.time.LocalDateTime.now()
andjava.time.ZonedDateTime.now()
will give you representations2 for the current date / time.
Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations.
With Java 8 and later, the standard java.time
package is recommended. Joda time is now considered "obsolete", and the Joda maintainers are recommending that people migrate.3.
1 - System.currentTimeMillis()
gives the "system" time. While it is normal practice for the system clock to be set to (nominal) UTC, there will be a difference (a delta) between the local UTC clock and true UTC. The size of the delta depends on how well (and how often) the system's clock is synced with UTC.
2 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: "It cannot represent an instant on the time-line without additional information such as an offset or time-zone."
3 - Note: your Java 8 code won't break if you don't migrate, but the Joda codebase may eventually stop getting bug fixes and other patches. As of 2020-02, an official "end of life" for Joda has not been announced, and the Joda APIs have not been marked as Deprecated.
Get date in current timezone in Java
Here is a way to get the id of a TimeZone
that matches your local system clock's offset,
Calendar cal = Calendar.getInstance();
long milliDiff = cal.get(Calendar.ZONE_OFFSET);
// Got local offset, now loop through available timezone id(s).
String [] ids = TimeZone.getAvailableIDs();
String name = null;
for (String id : ids) {
TimeZone tz = TimeZone.getTimeZone(id);
if (tz.getRawOffset() == milliDiff) {
// Found a match.
name = id;
break;
}
}
System.out.println(name);
how to get current time from given timezone name in java?
I cannot advise more strongly against using the legacy java.util.Date
. You should use the appropriate java.time
class instead.
In java.time.ZonedDateTime
, you can create a time zone alias map and populate it as you please. It's not pretty, but it works.
Map<String, String> aliasMap = new HashMap<>();
aliasMap.put("IST", "Asia/Calcutta");
aliasMap.put("Indian Standard Time", "Asia/Calcutta");
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Indian Standard Time", aliasMap));
How get the current date and the timezone in numbers format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd | X");
System.out.println(sdf.format(new Date()));
gets close, but the time zone is printed with a leading zero:
2017/06/05 | +03
I suppose you could remove leading zeros from the time zone, if you need to:
SimpleDateFormat date = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat zone = new SimpleDateFormat("ZZZZZ"); // = +03:00
String tz = zone.format(new Date()).split(":")[0]
.replaceAll("^(\\+|-)0", "$1"); // = +3
System.out.println(sdf.format(new Date()) + " | " + tz);
which gives:
2017/06/05 | +3
Convert Date/Time for given Timezone - java
For me, the simplest way to do that is:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Will print in UTC
System.out.println(sdf.format(calendar.getTime()));
//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
//Will print on your default Timezone
System.out.println(sdf.format(calendar.getTime()));
Related Topics
Programmatically Shut Down Spring Boot Application
Create MySQL Database from Java
How to Check If a Date Object Equals Yesterday
Preparedstatement with Statement.Return_Generated_Keys
What Is the Regex for "Any Positive Integer, Excluding 0"
Hibernate: Flush() and Commit()
In What Situations Is the Copyonwritearraylist Suitable
Painted Content Invisible While Resizing in Java
How to Change the Size of the Font of a Jlabel to Take the Maximum Size
Why Java Opens 3 Ports When Jmx Is Configured
Difference Between List and Array
What Determines Kafka Consumer Offset
Firestore Query Documents Startswith a String
Compression and Decompression of String Data in Java
How to Define a Method Which Takes a Lambda as a Parameter in Java 8
Can You Write Virtual Functions/Methods in Java