I have a list of dates in the form of ddMMMyyyy stored in one single string. The dates may or may not be consecutive
I print those dates as individual dates. I want to remove that and use hyphen if the dates are consecutive.
For Example
13Aug2020
15Aug2020 - 18Aug2020
22Aug2020
Instead of
13Aug2020
15Aug2020
16Aug2020
17Aug2020
18Aug2020
22Aug2020
Code used to Print Dates :
mDateView.setText(mDateValue.replace(",", "\n"));
where mDateView is a Textview and mDateValue is the String containing all the dates seperated by Commas
Parse each string into a LocalDate object using a DateTimeFormatter. Search for how (if your search leads to a page using the old and troublesome SimpleDateFormat, avoid that). Create two variables for the start and end of the current interval. Store the first date into both. In a loop over the remaining dates:
If the current date is one day after the end, store it into the end, thus extending the interval by one day.
Otherwise print the current interval, see below for how. Then again store the current date into both start and end.
After the loop terminates, print the current interval.
How to print the current interval: if start and end are equal, print only one of them; otherwise print both with an en-dash between them. In either case format each printed date into the desired format, for example the original format using the same DateTimeFormatter.
To determine whether current date is one day after end, use the plusDays and the isEqual methods of LocalDate.
Question: Doesn’t LocalDate require Android API level 26?
LocalDate is part of java.time, the modern Java date and time API. 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 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 DateTimeFormatter
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.
Related
I had two edit text for user to enter time (24 hours format).
How could i get those times from Edittext and deduct 5 hours and 30 minutes from user selected time.
Reason for deducting time : Converting IST to UTC timezone.
My final output should be like - HH:MM:SS:Milleseconds (Ex : 18:25:30:245635).
Thanks in advance.
java.time
ZoneId zone = ZoneId.of("Asia/Kolkata");
String timeString = "18:25:30.245635";
LocalTime time = LocalTime.parse(timeString);
LocalTime utcTime = LocalDate.now(zone) // Today
.atTime(time) // Today at the time in question
.atZone(zone) // Date and time in IST
.toOffsetDateTime() // Convert to OffsetDateTime for the next step
.withOffsetSameInstant(ZoneOffset.UTC) // Convert to UTC
.toLocalTime(); // Extract only the time of day
System.out.println("UTC time: " + utcTime);
Output is:
UTC time: 12:55:30.245635
I have assumed today’s date. Please check if this assumption is right for you. While the UTC offset for Asia/Kolkata hasn’t changed much recently, other time zones change their offset twice a year.
I changed your time format to have a period (point) rather than a colon between the seconds and fraction of second as is customary. If you do require a colon there, you need a DateTimeFormatter for parsing.
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) 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.
Wikipedia article: ISO 8601
I have an integer that when I put on Google Sheets, it represents the date 14/10/1911 (integer value is 4305).
I need to do this same conversion in my code using Java. So I'll have an array of integer that goes down by a factor of 1 (like 4305, 4304, 4303...) and I need to convert these integers into date (14/10/1911, 13/10/1911, 12/10/1911...) using the same method that excel/sheets uses.
Any ideas?
Thanks
LocalDate msBaseDate = LocalDate.of(1899, Month.DECEMBER, 30);
int[] integers = { 4305, 4304, 4303 };
for (int integerValue : integers) {
LocalDate date = msBaseDate.plusDays(integerValue);
System.out.println(date);
}
Output from this snippet is:
1911-10-14
1911-10-13
1911-10-12
Excel and other Microsoft products and possibly other software too use December 30, 1899, as a base date and represent dates as a count of days since that date. So just add the number to that date. I am using LocalDate from java.time, the modern Java date and time API.
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) 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.
I get the datetime content in the below string format with offset time value from the source system.
2019-02-16T10:00:00+08:00
Where i want to convert that into local date time using the offset value.I tried the below, but not getting the expected result.
DateTime date = new DateTime("2019-02-16T10:00:00+08:00");
-->output == 2019-02-16T02:00:00.000Z (the hour is decreased instead of increasing)
DateTime date = new DateTime("2019-02-16T10:00:00-08:00");
-->output == 2019-02-16T18:00:00.000Z (the hour is increased instead of decreasing).
is there any simple way to the expected output?
Note: I am using Java 1.7
What you are doing is correct. To get the time in your local time zone:
DateTime date = new DateTime("2019-02-16T10:00:00+08:00");
DateTime dateTimeInLocalTimeZone = date.withZone(DateTimeZone.getDefault());
System.out.println(dateTimeInLocalTimeZone);
On my computer in Europe/Copenhagen time zone I got
2019-02-16T03:00:00.000+01:00
As has been said in the comments, +08:00 is the offset that has already been added compared to UTC time. So your string denoted the same point in time as 2019-02-16T02:00:00+00:00. It may also be written as 2019-02-16T02:00:00Z since Z (pronounced “Zulu”) means UTC.
java.time and ThreeTen Backport
If you are not already tied to Joda-Time, you may prefer to use java.time, the modern Java date and time API. The code is similar:
OffsetDateTime sourceDateTime = OffsetDateTime.parse("2019-02-16T10:00:00+08:00");
ZonedDateTime dateTimeInLocalTimeZone = sourceDateTime.atZoneSameInstant(ZoneId.systemDefault());
2019-02-16T03:00+01:00[Europe/Copenhagen]
Question: Can I use java.time on Java 1.7?
Note: I am using Java 1.7
No big problem, java.time just requires at least Java 6. I have run the above code on jdk1.7.0_79.
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.
Another way to do that :
String dt = "2019-02-16T10:00:00+08:00";
ZonedDateTime zd = ZonedDateTime.parse("2019-02-16T10:00:00+08:00");
System.out.println(zd.toLocalDateTime().plusSeconds(zd.getOffset().getTotalSeconds()));
Output
2019-02-16T18:00
I've taken all of the answers given on SOF and other websites and tried to do this:
String fromDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssX").format(new DateTime().plusMonths(-6));
But I'm being given the exception:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
What am I doing wrong?
java.time
String fromDateTime = OffsetDateTime.now(ZoneId.systemDefault()).minusMonths(6).toString();
System.out.println(fromDateTime);
Output when running on my computer just now:
2018-08-04T12:45:34.087966+01:00
java.time is the modern Java date and time API and has effectively replaced Joda-Time. From the home page:
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).
In the code I am taking advantage of the fact that the java.time classes’ toString methods produce ISO 8601 format, the format you were asking for. I find it unlikely that the extra decimals on the seconds will pose any problem since thay are allowed within the standard.
Joda-Time
String fromDateTime = new DateTime().minusMonths(6).toString();
Example output:
2018-08-04T12:50:36.071+02:00
new DateTime() only has millisecond precision. You will always get exactly 3 decimals on the seconds.
I gotta use old java libraries, cause I work for a company that uses java version < 8
java.time works nicely on Java 6 and 7 too, and all things being equal I recommend it over Joda-Time. Only if forced to use Java 5, Joda-Time is no doubt the good choice.
In Java 8 and later and on newer Android devices (from API level 26) java.time 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.
What went wrong in your code?
Your code can be compiled without signs of errors, but issues a java.lang.IllegalArgumentException: Cannot format given Object as a Date when run. This is because a SimpleDateFormat cannot format a Joda-Time DateTime object. We would of course have expected this to be reported on compile time. But in addition to SimpleDateFormat.format(Date) there is also an overridden format(Object) inherited from Format. It works for formatting either a Date or a Number (for milliseconds since the epoch). This method is the one that the compiler chooses when you pass a DateTime. Which is why there is no compile-time error message.
Tip: When you don’t immediately understand an error message, paste it into your search engine. It will very often lead you to an explanation and a solution. Also in this case.
Links
Joda-Time home page
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.
Wikipedia article: ISO 8601
Sister question: Java : Cannot format given Object as a Date.
Try the following:
String fromDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssX").format(new DateTime().minusMonths(6).toDate());
You have to convert the DateTime to a Date before formatting, using the toDate() method will do the job.
API for toDate() and API for minusMonths, I would recommend to you check the API for new methods
I am trying to convert an excel formula into Kotlin code. But I am facing issue in converting a double into duration. The Excel displays in duration format. How do I convert to Duration format? I cant use Duration as API level is less than 26.
The result in
Excel Duration format - 0:47:22
Excel Number format - 0.03288861121
I am able to get it in the number format. But unable to convert it into time duration.
I am unsure whether the following is the best solution. You may be able to get something better from Excel somehow. In any case it works.
double durationDoble = 0.03288861121;
Duration dur = Duration.ofNanos((long) (durationDoble * TimeUnit.DAYS.toNanos(1)));
System.out.println(dur);
This prints
PT47M21.576008544S
If you are not used to the Duration class and/or ISO 8601 format, it may look a bit funny, but it means 47 minutes 21.576 seconds, so if rounded to whole seconds it agrees with what you expected.
I cant use Duration as API level is less than 26.
Yes, you can use Duration from java.time (the modern Java date and time API) in API levels less than 26. Add ThreeTenABP to your Android project and make sure to import org.threeten.bp.Duration.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
ThreeTen Backport project (ThreeTen for JSR-310, where java.time was first described)
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java Specification Request (JSR) 310.