How to convert UTC time into local time in Java? - java

I have time coming from gpslocation service in 1352437114052 format. Can some one tell me how to convert this into local time either in Java or Matlab or Excel.

Create a new Date from your milliseconds since epoch. Then use a DateFormat to format it in your desired timezone.
Date date = new Date(1352437114052L);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
format.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println(format.format(date));

This is an epoch time and it represents Fri, 09 Nov 2012 04:58:34 GMT. This numeric value is an absolute point in time, irrespective to time zone.
If you want to see that point in time in different time zone, use GregorianCalendar:
Calendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"));
c.setTimeInMillis(1352437114052L);
c.get(Calendar.HOUR_OF_DAY); //20:58 the day before

The modern Java answer using the JVM’s time zone setting (typically the same as your computer’s time zone):
long time = 1_352_437_114_052L;
ZonedDateTime dateTime = Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault());
System.out.println(dateTime);
Running on my computer I get
2012-11-09T05:58:34.052+01:00[Europe/Copenhagen]
To specify a time zone:
ZonedDateTime dateTime = Instant.ofEpochMilli(time).atZone(ZoneId.of("Asia/Almaty"));
2012-11-09T10:58:34.052+06:00[Asia/Almaty]
Question: Will that work on Android too?
To answer tinker’s comment here: Yes. I am using java.time, the modern Java date and time API, and it works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

#Steve Kuo answered the question directly, almost. Here's a more general solution for machine's local time, including daylight saving time, where a is of type BasicFileAttributes as reported from Windows directory entry in public FileVisitResult visitFile(Path f, BasicFileAttributes a) during Files.walkFileTree:
String modifyDate;
Date date = new Date(a.lastModifiedTime().to(TimeUnit.MILLISECONDS));
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
format.setTimeZone(TimeZone.getDefault());
modifyDate = (format.format(date)).substring(0,10);

long timeStamp = System.currentTimeMillis();
System.out.println(timeStamp+"");
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timeStamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a z");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString);
Output :
timestamp : 1528860439258
dateformat from sdf : 2018-06-12 08:27:19 PM PDT

Since new Date(String string) is deprecated now(which is the accepted answer), we can use DateTimeZone.getDefault() to get the system time zone
public String getZonedDate(String dateStr) {
DateTime utcDateTime = new DateTime(dateStr).toDateTime(DateTimeZone.UTC);
return utcDateTime
.toDateTime(DateTimeZone.getDefault()).toString("yyyy-MM-dd'T'HH:mm:ss");
}

Related

time convert issue while converting adding one day extra

I am trying to convert time zone, but it's adding one day extra from java function.
"" deActivationDate=2021-06-25T23:59:59.000+0000"";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
try {
Date date =formatter.parse(deActivationDate);
deActivationDate=formatter.format(date);
LOGGER.info("time format printing 1" +deActivationDate);//2021-06-26T04:29:59.000+0430
deActivationDate = deActivationDate.substring(0, deActivationDate.length()-2)+":30";
LOGGER.info("time format printing 2" +deActivationDate);//2021-06-26T04:29:59.000+04:30""
In above deactivation date is 25 when I am giving input but after formater parase method its converting as 26 why one day os getting add how to avoid it.
java.time through ThreeTen Backport
You should seriously consider using java.time, the modern Java date and time API, for your non-trivial date and time work.
It’s not very clear from your question, but I think that you want to convert the date and time string to the same date and wall-clock time in your own time zone, in this case, Asia/Tehran time zone. So a different point in time: near the end of the day in Iran rather than near the end of the day in UTC. And with a colon in the UTC offset.
I am declaring two formatters, one for parsing without colon and one for formatting back with colon:
private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.appendPattern("xx")
.toFormatter();
private static final DateTimeFormatter PRINTER = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.appendPattern("xxx")
.toFormatter();
Now your conversion goes like this:
String deActivationDate = "2021-06-25T23:59:59.000+0000";
OffsetDateTime dateTime = OffsetDateTime.parse(deActivationDate, PARSER);
deActivationDate = dateTime.atZoneSimilarLocal(ZoneId.systemDefault())
.format(PRINTER);
System.out.println("time format printing: " +deActivationDate);
Output is — tested on Java 1.7.0_67 with ThreeTen Backport version 1.3.6:
time format printing: 2021-06-25T23:59:59+04:30
Java knows that Asia/Tehran time zone uses summer time (DST) on June 25, so converts to and prints your desired offset of +04:30. Had the date been in the standard time part of the year, +03:30 would have been printed instead.
The 0 milliseconds are not printed, which for most purposes is an advantage. The format is ISO 8601, and according to the ISO 8601 standard the fraction of second is optional when it is 0. If you require the millis to be there, use this simpler formatter instead:
private static final DateTimeFormatter PRINTER
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxxx");
time format printing: 2021-06-25T23:59:59.000+04:30
Half-open: You should not represent the end of the day by 1 second before the start of the new day. First, it’s wrong: the day does not end a second before it ends. Second, it may give rise to errors because of times that fall within that last second and therefore in your program will neither belong to one day or the other. Even if this does not happen in practice, you will have programmers wasting their time wondering whether it may happen. Instead represent the end of the day as the first moment of the following day exclusive (typically 00:00). When testing, require a time to be strictly before the end of the day to belong to the day. This approach is standard for all kinds of intervals and certainly for time intervals. They are then known as half-open intervals.
Question: Doesn’t java.time require Java 8?
java.time works nicely on Java 7. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
Here's the fix for your code. Though we recommend not to do it via substring method.
String deActivationDate="2021-06-25T23:59:59.000+0000";
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date =formatter.parse(deActivationDate);
deActivationDate=formatter.format(date);
System.out.println("time format printing 1: " +deActivationDate);
//2021-06-25T23:59:59.000+0000
deActivationDate = deActivationDate.substring(0,
deActivationDate.length()-4)+"0430";
System.out.println("time format printing 2: " +deActivationDate);
//2021-06-25T23:59:59.000+0430
} catch (Exception e) {
System.err.println(e.getMessage());
}
Thanks to all for your suggestion #beshambher-chaukhwan m i have achieved changes with below code
String deActivationDate="2021-06-25T23:59:59.000+0000";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
try {
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date =formatter.parse(deActivationDate);
deActivationDate=formatter.format(date);
if(TimeZone.getDefault().useDaylightTime()) {
deActivationDate = deActivationDate.substring(0, deActivationDate.length()-4)+"04:30";
}else {
deActivationDate = deActivationDate.substring(0, deActivationDate.length()-4)+"03:30";
}

Converting dates time to other timezones

how to I convert date time to others time zone using java.
example : 11 June 2021 20:00 to 11 June 2021 06:00 PM
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date parsed = format.parse("2021-03-01 20:00");
*\\to//*
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm z");
Date parsed = format.parse("2021-03-01 06:00 PM");
like this
First of all you should use the new java 8 API for data and time, java.time, secondly you need to have a zone to convert to and from. Here I have assumed you want to use the zone of the device (and convert to GMT) as from and GMT as to.
String input = "2021-03-01 20:00";
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.systemDefault());
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd h:mm a").withZone(ZoneId.of("GMT"));
TemporalAccessor date = inputFormatter.parse(input);
String output = outputFormatter.format(date);
System.out.println(output);
Joakim Danielson is on to the right thing in his answer: use java.time, the modern Java date and time API, for your date and time work. My solution roughly follows the same overall pattern. There are some details I’d like to show you.
private static final DateTimeFormatter inputFormatter
= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private static final DateTimeFormatter outputFormatter
= DateTimeFormatter.ofPattern("yyyy-MM-dd h:mm a");
DateTimeFormatter is thread-safe so there’s no problem instantiating them only once even if they are used from different threads.
String input = "2021-03-01 20:00";
String output = LocalDateTime.parse(input, inputFormatter)
.atZone(ZoneId.systemDefault())
.withZoneSameInstant(ZoneOffset.UTC)
.format(outputFormatter);
System.out.println(output);
Output is the same as from Joakim’s code. In my time zone (Europe/Copenhagen) it is:
2021-03-01 7:00 PM
java.time lends itself well to a fluent writing style. Why not exploit it? Since conversion to a different time zone was the point, I prefer to make it explicit in the code. The withZoneSameInstant() call makes the conversion. And I prefer to parse into either LocalDateTime or ZonedDateTime rather than using the low-level TemporalAccessor interface directly. The documentation of the interface says:
This interface is a framework-level interface that should not be
widely used in application code. Instead, applications should create
and pass around instances of concrete types, such as LocalDate.
There are many reasons for this, part of which is that implementations
of this interface may be in calendar systems other than ISO. …
I need api 21 support. This is not available on api 21
Indeed java.time works nicely on Android API level 21.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Documentation of TemporalAccessor
Question: cannot resolve symbol 'java.time.LocalDate' error in android studio about using java.time on earlier Andoird
Question: Android - Date in API Level 21 [closed]
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
You must get your date format to a specific zone, as you have not mentioned in the post, i will give 1 sample below,
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(yyyy-MM-dd HH:mm);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Now using this simpleDateFormat for your specific timezone, you can format the value.
The key to the solution is to get the zone offset between two date-times which you can calculate with Duration#between and then change the zone offset of the first date-time into that of the second one (which is equal to the hours and minutes part of the calculated duration.
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Given date-time strings
String strOne = "11 June 2021 20:00";
String strTwo = "11 June 2021 06:00 PM";
// Respective formatters
DateTimeFormatter dtfOne = DateTimeFormatter.ofPattern("dd MMMM uuuu HH:mm", Locale.ENGLISH);
DateTimeFormatter dtfTwo = DateTimeFormatter.ofPattern("dd MMMM uuuu hh:mm a", Locale.ENGLISH);
// Respective instances of LocalDateTime
LocalDateTime ldtOne = LocalDateTime.parse(strOne, dtfOne);
LocalDateTime ldtTwo = LocalDateTime.parse(strTwo, dtfTwo);
// Duration between the two date-times
Duration duration = Duration.between(ldtOne, ldtTwo);
int hours = duration.toHoursPart();
int minutes = duration.toMinutesPart();
// Zone offset with hours and minutes of the duration
ZoneOffset zoneOffset = ZoneOffset.ofHoursMinutes(hours, minutes);
//
ZonedDateTime zdt = ldtOne.atZone(ZoneId.systemDefault()) // ZonedDateTime using JVM's time zone
.withZoneSameInstant(zoneOffset); // ZonedDateTime using the given zone offset
System.out.println(zdt);
String formatted = zdt.format(dtfTwo);// Format the given ZonedDateTime using the given formatter
System.out.println(formatted);
}
}
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API. Learn more about the modern date-time API at Trail: Date Time.
Note: If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Parsing a string to a datetime does not return the correct time

In Android...I am expecting 3:12 pm as time out put of the following code but I get 4:12 pm. Whats the correct way to parse this date time format.
String dt = "2018-09-02T19:12:00-0400";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
Date date = dateFormat.parse(dt);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
Time zone
It’s best to specify explicitly in which time zone you want your output:
DateTimeFormatter inputFormatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXX");
DateTimeFormatter displayFormatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.ENGLISH);
ZoneId displayZone = ZoneId.of("Pacific/Pitcairn");
String dt = "2018-09-02T19:12:00-0400";
OffsetDateTime dateTime = OffsetDateTime.parse(dt, inputFormatter);
String displayDateTime = dateTime.atZoneSameInstant(displayZone)
.format(displayFormatter);
System.out.println(displayDateTime);
This prints:
September 2, 2018 at 3:12:00 PM PST
I have used Pacific/Pitcairn time zone in my code, but you know better which time zone you want.
I am also using java.time, the modern Java date and time API. The date-time classes you are using, SimpleDateFormat and Date, are considered long outdated, and java.time is so much nicer to work with.
What went wrong in your code?
Your way of parsing your date string is correct and produces the correct Date.
When printing the Date, you are implicitly calling toString. The outdated Date class has a peculiar and confusing toString method: it grabs the JVM’s time zone setting and uses it for producing the string. So depending on your default time zone, you can get any hour of day in the output. So it seems your JVM’s time zone setting didn’t correspond to what you had expected.
Since you expected 3:12 PM from your input of 19:12:00-0400, I take it that you want a time zone that is at offset -08:00 from UTC in September. If for example your default time zone was America/Los_Angeles, the standard time of which is at -08:00, you would get Sun Sep 02 16:12:00 PDT 2018 because summer time (daylight saving time) is in effect in California in September, so the offset is -07:00.
Relying on your JVM’s default time zone is always fragile since the setting may be changed at any time by other parts of your program or by other programs running in the same JVM.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

How to get day of week name from selected date month and year in Android?

I tried the below code but it gives me the name of the day of week two days ago.
DatePicker picker;
int date = picker.DayOfMonth;
int month = (picker.Month + 1);//month is 0 based
int year = picker.Year;
SimpleDateFormat simpledateformat = new SimpleDateFormat("EEE");
Date dt = new Date(year, month, date);
First convert your Date in to specific Date format using SimpleDateFormat
Use SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE"); to get Day name in week
WHERE EEEE -> Day name in week
SAMPLE CODE
SimpleDateFormat inFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date myDate = inFormat.parse(date+"-"+month+"-"+year);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
String dayName=simpleDateFormat.format(myDate);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE", Locale.US);
String asWeek = dateFormat.format(dt);
DateTimeFormatter dayOfWeekFormatter
= DateTimeFormatter.ofPattern("EEE", Locale.ENGLISH);
LocalDate date = LocalDate.of(
picker.getYear(), picker.getMonth(), picker.getDayOfMonth());
System.out.println(date.format(dayOfWeekFormatter));
Picking 2018-04-09 this printed
Mon
I am using and recommending java.time, the modern Java date and time API. The Date class is long outdated, and you are using a deprecated constructor. It was deprecated because it works unreliably across time zones, so you shouldn’t. SimpleDateFormat is not only outdated, it is also notoriously troublesome. I recommend you avoid those classes altogether. The modern API is so much nicer to work with.
What went wrong in your code?
You’ve got two bugs apart from using the deprecated Date constructor and the outdated classes:
It’s the Date’s month that is 0-based (not that of DatePicker), so you need to subtract 1, not add 1 (or maybe they are both 0-based??).
The deprecated Date constructor’s year is “1900-based”. This may have seemed a good idea when the class was designed in the 1990’s: you could just specify 95 to get 1995. When you pass 2018 to the constructor, you get year 3918. That’s right. :-(
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Calendar calendar = Calendar.getInstance();
DateFormat date4= new SimpleDateFormat("EEEE", Locale.getDefault());
String localTime4 = date4.format(calendar.getTime());
Simple and easy way
just use this

How to get TimeZone from android mobile?

I want to get the time zone from the Android mobile when clicking a button.
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
TimeZone tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezone id :: " +tz.getID());
Output:
TimeZone GMT+09:30 Timezone id :: Australia/Darwin
Edit: corrected the case
TimeZone.getDefault()
I needed the offset that not only included day light savings time but as a numerial. Here is the code that I used in case someone is looking for an example.
I get a response of "3.5" (3:30') which is what I would expect in Tehran , Iran in winter and "4.5" (4:30') for summer .
I also needed it as a string so I could post it to a server so you may not need the last line.
for getting currect time zone :
TimeZone tz = TimeZone.getDefault();
Date now = new Date();
//Import part : x.0 for double number
double offsetFromUtc = tz.getOffset(now.getTime()) / 3600000.0;
String m2tTimeZoneIs = Double.parseDouble(offsetFromUtc);
Try this code-
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
It will return user selected timezone.
ZoneId from java.time and ThreeTenABP
Modern answer:
ZoneId zone = ZoneId.systemDefault();
System.out.println(zone);
When I ran this snippet in Australia/Sydney time zone, the output was exactly that:
Australia/Sydney
If you want the summer time (DST) aware time zone name or abbreviation:
DateTimeFormatter longTimeZoneFormatter = DateTimeFormatter.ofPattern("zzzz", Locale.getDefault());
String longTz = ZonedDateTime.now(zone).format(longTimeZoneFormatter);
System.out.println(longTz);
DateTimeFormatter shortTimeZoneFormatter = DateTimeFormatter.ofPattern("zzz", Locale.getDefault());
String shortTz = ZonedDateTime.now(zone).format(shortTimeZoneFormatter);
System.out.println(shortTz);
Eastern Summer Time (New South Wales)
EST
The TimeZone class used in most of the other answers was what we had when the question was asked in 2011, even though it was poorly designed. Today it’s long outdated, and I recommend that instead we use java.time, the modern Java date and time API that came out in 2014.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
Edit: On (older) Android usually, as long as you're on Android Gradle plugin 4.0 or newer, with coreLibraryDesugaring you can use java.time directly. ThreeTenABP is no longer needed. (Previous bullet: use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.)
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
TimeZone timeZone = TimeZone.getDefault();
timeZone.getID();
It will print like
Asia/Kolkata
On my device, TimeZone.getDefault() is always returning the UTC time zone.
I need to do this to get the user-configured time zone:
TimeZone.setDefault(null)
val tz = TimeZone.getDefault()
It will return the user-selected time zone.
Simplest Solution With Simple Date Format:
SimpleDateFormat("ZZZZZ"):
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("ZZZZZ",Locale.getDefault());
String localTime = date.format(currentLocalTime);
System.out.println(localTime+ " TimeZone " );
==> Output is : +05:30
All the answers here seem to suggest setting the daylight parameter to false. This is incorrect for many time zones which change abbreviated names depending on the time of the year (e.g., EST vs. EDT).
The solution below will give you the correct abbreviation according to the current date for the time zone.
val tz = TimeZone.getDefault()
val isDaylight = tz.inDaylightTime(Date())
val timezone = tz.getDisplayName(isDaylight, TimeZone.SHORT)
According to http://developer.android.com/reference/android/text/format/Time.html you should be using Time.getCurrentTimezone() to retrieve the current timezone of the device.
For devices with API 26 and higher, you can get it like this:
ZonedDateTime.now().getZone().toString();

Categories

Resources