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.
Related
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.
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'm converting a VB.Net program to Java and I have to convert following line
Dim s = Now.ToString("yyyy-MM-dd")
I have written following Java code
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String s = sdf.format(d);
that I can write on one line
String s = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
What is the shorter code in Java that works in Java 6 and greater ?
Is there some Java codes that generates date formatted string in calling a method of Date object (example: Date.format("yyyy-MM-dd")) ?
What is the shorter code in Java that works in Java 6 and greater ?
I’d like to answer the “Java 6 and greater” part: The code in deHaar’s answer does. My version would be either
String now = LocalDate.now(ZoneId.systemDefault()).toString();
or
DateTimeFormatter customFormatter = new DateTimeFormatter.ofPattern("uuuu-MM-dd");
String now = LocalDate.now(ZoneId.systemDefault()).format(customFormatter);
In Java 8 and later and on newer Android devices (from API level 26) java.time, 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.
Wikipedia article: ISO 8601
From Java 8 on, there is java.time with several useful classes.
If you may / can use Java 8 or higher, then you can do the following:
String now = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
which will output 2018-12-05 today in my time zone (may differ in yours).
You just need to
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
in order to make it work.
You can as well apply custom formattings with
DateTimeFormatter customFormatter = new DateTimeFormatter.ofPattern("yyyy-MM-dd");
String now = LocalDate.now().format(customFormatter);
I'm trying to add event but it shows a different date that I'm trying to put and what I'm getting.
eventButton.setOnClickListener(
new Button.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendarEvent = Calendar.getInstance();
Intent calendarIntent = new Intent(Intent.ACTION_EDIT);
calendarIntent.setType("vnd.android.cursor.item/event");
Calendar time = Calendar.getInstance();
time.clear();
time.set(2018, 05, 23);
calendarIntent.putExtra(CalendarContract.Events.TITLE, "Whatever");
calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,time.getTimeInMillis());
calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,time.getTimeInMillis());
calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY,true);
calendarIntent.putExtra(CalendarContract.Events.RRULE, "FREQ=YEARLY");
startActivity(calendarIntent);
}
}
);
I'm getting this Jun 22, instead of May 23:
screenshot
long eventTimeInMillis = LocalDate.of(2018, Month.MAY, 23)
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
As Jamie Corkhill said in a comment, you need the time at the start of day (00:00) in UTC. The above code not only gives you the time at 00:00 in UTC, it is also pretty clear about that this is what it gives you.
I am using java.time, the modern Java date and time API. I find it much nicer to work with than the long outdated Calendar class.
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.
The Java Calendar.set() method counts months just like arrays in programming, starting from 0 for January. Therefore, your month should be 4 for May, since January is 0, February is 1, March is 2, and so on. That is what I believe is causing your issue.
You may also use the Month enumeration. That is, instead of using your line
time.set(2018, 05, 23);
Use
time.set(2018, Calendar.May, 23);
I hope this helps.