Get current time in a given timezone : android
I got it to work like this :
TimeZone tz = TimeZone.getTimeZone("GMT+05:30");
Calendar c = Calendar.getInstance(tz);
String time = String.format("%02d" , c.get(Calendar.HOUR_OF_DAY))+":"+
String.format("%02d" , c.get(Calendar.MINUTE))+":"+
. String.format("%02d" , c.get(Calendar.SECOND))+":"+
. String.format("%03d" , c.get(Calendar.MILLISECOND));
Also, every other time conversion based on this date should also be used with this timezone, otherwise, the default timezone of device will be used and the time will be converted based on that timezone.
Android / JAVA: Get current time based on timezone
Malaysia observes GMT+8, and you can set the TimeZone
of your SimpleDateFormat
like
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
String time = "Current time - " + format.format(calendar.getTime());
Or, better, switch to the ThreeTenABP backport of java.time
like
ZonedDateTime klDateTime = LocalDateTime.now().atZone(ZoneId.of("Asia/Kuala_Lumpur"));
String time = "Current time - " + klDateTime.format(DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss"));
How to get current time and date in Android
You could use:
import java.util.Calendar;
import java.util.Date;
Date currentTime = Calendar.getInstance().getTime();
There are plenty of constants in Calendar for everything you need.
Check the Calendar class documentation.
Bug retrieving current time on Android with a given timezone
A date-time != span-of-time
You are abusing the date-time class java.util.Calendar
(or java.util.Date
) to inappropriately track a span of time. That class tracks time as a count of milliseconds since the epoch of start of 1970 in UTC (1970-01-01T00:00:00Z
) plus an assigned time zone.
So when you instantiate with a count of milliseconds of 5 minutes, you are actually creating a date-time of 5 minutes after start of 1970, 1970-01-01T00:05:00Z
for a java.util.Date
and adding a time zone for java.util.Calendar
.
When you applied a time zone for Malaysia you end up getting the old-style Malaysia time rules for 1970, not today’s post-1981 Malaysia rules.
So, no bugs, just a misuse of features.
Lesson learned: Do not use a date-time value to represent a span-of-time.
java.time
Another problem: You are using the notoriously troublesome old legacy date-time classes, now supplanted by the java.time classes.
If by “unix timestamp” you meant a count of milliseconds from an epoch of 1970 in UTC such as 1_473_738_754_764L
, then use the Instant
class. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds.
First, we simulate some input data as described in Question as being in the future up to 15 minutes.
Instant instantNow = Instant.now ();
long seconds = TimeUnit.MINUTES.toSeconds ( 10 );
String input = Long.toString ( instantNow.plusSeconds ( seconds ).toEpochMilli () ); // 10 minutes in the future.
To process that String input, we convert to a long
primitive value, and feed it to a Instant
factory method.
Instant instantLater = Instant.ofEpochMilli ( Long.valueOf ( input ) );
Span-of-time
To capture the elapsed time, use the Duration
class.
Duration duration = Duration.between ( instantNow , instantLater );
System.out.println ( "instantNow: " + instantNow + " | instantLater: " + instantLater + " | duration: " + duration );
When run. Note the standard ISO 8601 format for a duration PnYnMnDTnHnMnS
where P
marks the beginning and the T
separates the years-months-days portion from the hours-minutes-seconds portion. So PT10M
is “ten minutes”. Always use this format for textual representation of elapsed time rather than ambiguous clock-style (HH:MM:SS). The Duration
and Period
classes in java.time can parse and generate such strings directly with no need to specify a formatting pattern.
instantNow: 2016-09-13T19:16:33.913Z | instantLater: 2016-09-13T19:26:33.913Z | duration: PT10M
Note that none of the above code cared about time zones. All the values were in UTC. Much of your business logic, data storage, and data exchange should be in UTC. Only use zoned values where necessary or for presentation to the user.
Zoned
Your Questions asked about zoned values for Rome and for Malaysia. Apply a ZoneId
to get a ZonedDateTime
. Specify a proper time zone name. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId zMontreal = ZoneId.of ( "America/Montreal" );
ZoneId zRome = ZoneId.of ( "Europe/Rome" );
ZoneId zKualaLumpur = ZoneId.of ( "Asia/Kuala_Lumpur" );
ZonedDateTime zdtMontreal = instantNow.atZone ( zMontreal );
ZonedDateTime zdtRome = instantNow.atZone ( zRome );
ZonedDateTime zdtKualaLumpur = instantNow.atZone ( zKualaLumpur );
System.out.println ( "instantNow: " + instantNow + " | zdtMontreal: " + zdtMontreal + " | zdtRome: " + zdtRome + " | zdtKualaLumpur: " + zdtKualaLumpur );
instantNow: 2016-09-13T20:23:34.280Z | zdtMontreal: 2016-09-13T16:23:34.280-04:00[America/Montreal] | zdtRome: 2016-09-13T22:23:34.280+02:00[Europe/Rome] | zdtKualaLumpur: 2016-09-14T04:23:34.280+08:00[Asia/Kuala_Lumpur]
Android - Converting current date and time with timezone
tl;dr
Use java.time classes.
OffsetDateTime // Represent a moment as a date, a time-of-day, and an offset-from-UTC (a number of hours, minutes, seconds) with a resolution as fine as nanoseconds.
.now( // Capture the current moment.
ZoneOffset.UTC. // Specify your desired offset-from-UTC. Here we use an offset of zero, UTC itself, predefined as a constant.
) // Returns a `OffsetDateTime` object.
.format( // Generate text in a `String` object representing the date-time value of this `OffsetDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSSSSxxxxx" , Locale.US )
) // Returns a `String` object.
2018-09-27T05:39:41.023987+00:00
Or, use Z
for UTC.
Instant.now().toString()
2018-09-27T05:39:41.023987Z
java.time
The modern approach uses the java.time that supplanted the terrible old date-time classes.
Specifically:
- Use
Instant
orOffsetDateTime
instead ofjava.util.Date
. - Use
DateTimeFormatter
instead of `SimpleDateFormat.
Get the current time in UTC. We use the OffsetDateTime
class rather than Instant
for more flexible formatting when generating text.
ZoneOffset offset = ZoneOffset.UTC;
OffsetDateTime odt = OffsetDateTime.now( offset );
Define a formatting pattern to match your desired output. Note that the built-in formatting patterns use Z
as standard shorthand for +00:00
. The Z
means UTC and is pronounced “Zulu”. This Zulu time format is quite common. I suggest using such formats with Z
. But you asked explicitly for the long version of an offset-from-UTC of zero, so we must use a custom DateTimeFormatter
object.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSSSSxxxxx" , Locale.US );
String output = odt.format( f );
2018-09-27T05:39:41.023987+00:00
FYI, the formats discussed here comply with the ISO 8601 standard.
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 the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
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….
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 to get TimeZone from android mobile?
Have you tried to use TimeZone.getDefault()
:
Most applications will use TimeZone.getDefault() which returns a TimeZone based
on the time zone where the program is running.
Ref: http://developer.android.com/reference/java/util/TimeZone.html
Getting the current time zone in android application
Use this
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
Log.d("Time zone","="+tz.getDisplayName());
or you can also use the java.util.TimeZone
class
TimeZone.getDefault().getDisplayName()
Related Topics
Android How to Sort JSONarray of JSONobjects
How to Ask Permission to Access Gallery on Android M.
What Is the Use of Memoryfile in Android
Android Java.Net.Unknownhostexception: Host Is Unresolved (Strategy Question)
How to Highlight Multiple Words in Edittext
Read Data from SQLite Where Column Name Contains Spaces
Android JSON Parsing of Multiple JSONobjects Inside JSONobject
Android - Viewrootimpl$Calledfromwrongthreadexception
Read/Write .Txt File with Special Characters
What Is the Correct Way to Do Inserts/Updates/Deletes in Android SQLitedatabase Using a Query String
Android:Table Has No Column Named "Variable Name" MySQL Database Error
Google Cloud Messaging: Don't Receive Alerts When iOS App Is in Background
Java Apns Certificate Error with "Derinputstream.Getlength(): Lengthtag=109, Too Big."
Can't Install Rjava on Ubuntu System
Unable to Compile Jni Program Rjava