Date difference in days is different in different location environment - java

Below is giving me 279 days in local but in different server it is giving me 278 why this happening ?
String sDate = "10-11-2017";
String eDate = "16-08-2018";
Date startDate = new SimpleDateFormat(MsmConstants.DATE_FORMAT).parse(sDate);
Date endDate = new SimpleDateFormat(MsmConstants.DATE_FORMAT).parse(eDate);
long difference = startDate.getTime() - endDate.getTime();
return Math.abs(difference / (1000 * 60 * 60 * 24));

This is probably coming from some kind of rounding combined with a difference in timezones.
Since both operands on the left and right of your / operator are integral types, you are actually losing precision with that operator.
If you change your expression to: (double) difference / (1000 * 60 * 60 * 24)
you will notice that the result is actually: -278.9583333333333
The reason it is not exact days is because of daylight savings and similar date/time adjustments.
If on your PC you have different regional settings from the server, which do not have the same daylight savings, then you might have got a different number, which exceeded 279.
As a sidenote, the Java 7 and earlier date/time API was very buggy. SimpleDateFormat wasn't even thread safe, and there were lots of issues with daylight savings and similar situations. You should really move to Java 8. What you are doing would simply become: Duration.between(startDate, endDate) and the calculation would be done correctly for you.
String sDate = "10-11-2017";
String eDate = "16-08-2018";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDateTime startDate = LocalDate.parse(sDate, formatter).atTime(0, 0);
LocalDateTime endDate = LocalDate.parse(eDate, formatter).atTime(0, 0);
return Duration.between(startDate, endDate).toDays();
You will see that this actually gives you 279.

jbx has already in another answer explained nicely what went wrong. 10 November is in winter on the Northern hemisphere, and 16 August is in summer. Between those two dates summer time (DST) begins, which causes one day to be just 23 hours, so the difference you calculate is 1 hour short of being 279 days at you had expected and had observed locally.
java.time
Date and time math is too complicated and error-prone to do yourself the way you tried. You should always leave it to a well-proven library. Here’s the correct and modern solution.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d-MM-uuuu");
String sDate = "10-11-2017";
String eDate = "16-08-2018";
LocalDate startDate = LocalDate.parse(sDate, dateFormatter);
LocalDate endDate = LocalDate.parse(eDate, dateFormatter);
long difference = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println(Math.abs(difference));
Output is the expected:
279
Since your date strings haven’t got time of day, there is no reason to use LocalDateTime. LocalDate is the correct class to use. It also makes sure that no number truncation can happen since there is always a whole number of days between two dates.
Question: Will that work on Java 7?
Yes, java.time 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 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 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.

SimpleDataFormat uses the JVM's default timezone to create Date objects. In case of daylight saving time, this might result in a +/- 1 day difference between two dates.
You have a couple of options:
Explicitly set the timezone of your SimpleDateFormat objects to GMT/UTC.
Explicitly set the timezone of your JVM to GMT/UTC.
In Java 8, use the new java.time API; in earlier versions of Java use an alternative like Joda Time.

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";
}

Converted unix timestamp with a timezone addition in seconds gives a true local date time on Android emulator but not in real device?

I took a date from a web service in UNIX timestamp. I milltuplied it by 1000L then I added the timezone to it in seconds (also provided by the web service) milltiplied by 1000 to obtain the date according to the country in which the application will run and not the UTC date.
In the emulator the date time provided is correct but when I tested on a real device it provided me the time with 1 hour more which does not correspond to the local time. Where is the problem?
long numberOfsecondsRise = json.getJSONObject("city").getInt("timezone");
long res=(json.getJSONObject("city").getLong("sunrise")*1000L +numberOfsecondsRise*1000) ;
Date rise=new java.util.Date(res);
DateFormat dfa = DateFormat.getTimeInstance();
sunFiled.setText(getResources().getString(R.string.sunrise)+": " + dfa.format(rise));
java.time and ThreeTenABP
Consider using java.time, the modern Java date and time API, for your time work. If for minSDK below API level 26, then through the backport, I will get back to that. First the code:
DateTimeFormatter timeFormatter
= DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM);
long sunriseUnixTs = 1_589_581_234;
ZonedDateTime sunriseApplicationTz = Instant.ofEpochSecond(sunriseUnixTs)
.atZone(ZoneId.systemDefault());
System.out.println("Sunrise: " + sunriseApplicationTz.format(timeFormatter));
Output from this example snippet in my time zone and locale:
Sunrise: 03.50.34
One of the things I find great about java.time is that the code makes it explicit that we are getting the time in the default time zone of the JVM where the application is running.
What went wrong in your code?
Adding the time zone offset of the city you are inquiring about is wrong. A Unix timestamp is independent of time zone. So if you multiply by 1000 and feed to new Date(long), you are getting a Date that holds the correct point in time. If you add a non-zero offset, you are getting a wrong point in time. Your emulator gave you the expected result, why, then? It might be because the offset from JSON was 0 (zero) or because the error was balanced out by the emulator using a different default time zone from what you had expected.
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).
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.
A question about an Android emulator that seems to be using UTC as its default time zone rather than the time zone of the host operating system: Emulated Android Device shows wrong date (Windows 10)
Date (long date) constructor documentation says:
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
This means the value is supposed to be in UTC. The time offset in seconds must be applied when formatting the date for display.
long numberOfsecondsRise = json.getJSONObject("city").getInt("timezone");
Date rise = new java.util.Date(json.getJSONObject("city").getLong("sunrise") * 1000L);
int offsetMinutes = numberOfsecondsRise / 60;
String sign = (offsetMinutes < 0 ? "-" : "+");
offsetMinutes = Math.abs(offsetMinutes);
String timeZoneID = String.format("GMT%s%d:%02d", sign, offsetMinutes / 60, offsetMinutes % 60);
DateFormat dfa = DateFormat.getTimeInstance();
dfa.setTimeZone(TimeZone.getTimeZone(timeZoneID));
sunFiled.setText(getResources().getString(R.string.sunrise) + ": " + dfa.format(rise));

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 parse time (hour, minute) from a string?

Anybody know how to parse time (hour, minute and AM/PM) from a string that looks like "01:20" -> 1:20AM and "21:20" -> 9:20PM? Most solutions out there seem to assume or require a Date or Calendar object.
My input time is actually coming from a TimePickerDialog (specifically, this MaterialDateTimePicker implementation, so I receive only the hourOfDay, minute and seconds (integers).
I want to be able to format the time that the user picked in a friendly way, i.e 12:30PM, 02:15AM, etc.
I am trying to use Joda Time:
fun formattedTime(timeStr: String): String {
// Get time from date
val timeFormatter = DateTimeFormat.forPattern("h:mm a")
val displayTime = timeFormatter.parseLocalTime(timeStr)
return displayTime.toString()
}
but I get this error with an input string such as "1:20":
java.lang.IllegalArgumentException: Invalid format: "1:20" is too short
I have also looked into SimpleDateFormat but it seems to require a full date-time string such as in this related question
As #ole-v-v pointed out, SimpleDateFormat has seen better days - so today you can make use of the java.time package to do the job:
java.time.format.DateTimeFormatter target2 =
java.time.format.DateTimeFormatter.ofPattern("h:mm a");
java.time.format.DateTimeFormatter source2 =
java.time.format.DateTimeFormatter.ofPattern("HH:mm");
System.out.println("01:30 -> " + target2.format(source2.parse("01:30")));
System.out.println("21:20 -> " + target2.format(source2.parse("21:20")));
Yields the result of
01:30 -> 1:30 AM
21:20 -> 9:20 PM
as expected.
In Joda-Time you would code it as #meno-hochschild pointed out in his answer below.
Using SimpleDateFormat it will look like this:
SimpleDateFormat target = new SimpleDateFormat("h:mm a");
SimpleDateFormat source = new SimpleDateFormat("HH:mm");
System.out.println("01:30 -> " + target.format(source.parse("01:30")));
System.out.println("21:20 -> " + target.format(source.parse("21:20")));
This will parse from 24h times to 12 hours display
01:30 -> 1:30 AM
21:20 -> 9:20 PM
It all depends on the format for the hours - for parsing you'll want 24h hours (format HH), for output you want 12 hours plus am / pm - format is h.
If you want 01:30 to be PM you'll have to add that to the string to be parsed somehow:
System.out.println("01:30 pm-> " + target.format(target.parse("01:30 pm")));
resulting in
01:30 pm-> 1:30 PM
The accepted answer is correct. However, I am astonished to see the old classes like SimpleDateFormat although the OP has explicitly first desired a Joda answer (see the tags of the question). So I post here the Joda answer as supplement:
DateTimeFormatter target = DateTimeFormat.forPattern("h:mm a").withLocale(Locale.ENGLISH);
DateTimeFormatter source = DateTimeFormat.forPattern("HH:mm");
System.out.println("01:30 -> " + target.print(source.parseLocalTime("01:30")));
System.out.println("21:20 -> " + target.print(source.parseLocalTime("21:20")));
01:30 -> 1:30 AM
21:20 -> 9:20 PM
I advise not to mix two different time libraries (the OP obviously uses Joda-Time-Android).
Your two good options are Joda-Time and java.time.
Since you receive hourOfDay, minute and seconds as integers from the time picker, you don’t need to do any parsing.
java.time
DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
.withLocale(Locale.US);
LocalTime time = LocalTime.of(hourOfDay, minute, second);
String displayTime = time.format(timeFormatter);
System.out.println(displayTime);
This prints the time like this:
11:45 PM
Rather than an explicit format pattern string I am relying on the built-in localized format for the US locale. It has put a space between the minutes and PM (or AM). I believe your users will be happy about that. If not, you will need to use DateTimeFormatter.ofPattern("h:mma", Locale.US) instead.
Joda-Time
If you are already using Joda-Time and don’t have a reason for changing at this point, sticking to it is reasonable. You may use the LocalTime(int hourOfDay, int minuteOfHour, int secondOfMinute) constructor. Then proceed as in Meno Hochschild’s answer. It’s a good and knowledgeable answer.
Note that Joda-Time is considered to be a largely “finished” project.
No major enhancements are planned. If using Java SE 8, please migrate
to java.time (JSR-310).
(Quoted from the Joda-Time homepage)
Stay away from SimpleDateFormat
Stay far away from the SimpleDateFormat class. It can be made to work for the job, but it is not only long outdated, it is also notoriously troublesome.
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.

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