Different/Incorrect results in calendar field - java

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.

Related

Android calendar get previous to previous month of previous year

I am facing issue with android calendar, I want to get previous to previous month, when i am trying it with current year this will achieve my goal, but when i am trying with previous year it fails. in my case today is 29/apr/2020 and i want feb/2019 return from calendar. please help me with this.
my code is following
Date dt = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int month = cal.get(Calendar.MONTH) - 2; // beware of month indexing from zero
int year = cal.get(Calendar.YEAR)-1;
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
String formatMonth = new SimpleDateFormat("MMM").format(cal.getTime());
String formatYear = new SimpleDateFormat("yy").format(cal.getTime());```
java.time and ThreeTenABP
Allow me to suggest that you use java.time, the modern Java date and time API, for your date work.
YearMonth currentMonth = YearMonth.of(2020, Month.APRIL);
YearMonth backThen = currentMonth.minusYears(1).minusMonths(2);
String formatMonth = backThen.format(DateTimeFormatter.ofPattern("MMM"));
String formatYear = backThen.format(DateTimeFormatter.ofPattern("yy"));
System.out.printf("Month %s; year %s%n", formatMonth, formatYear);
Output on my computer is (locale dependent):
Month feb.; year 19
For the sake of a reproducible example I hardcoded the year and month. To start from the current month in some time zone use something like this:
YearMonth currentMonth = YearMonth.now(ZoneId.of("Europe/Minsk"));
What went wrong in your code?
It’s the poor and confusing design of the Calendar and GregorianCalendar classes.
You said you ran your code on 29/apr/2020. This causes your Calendar to be set back to 29th February 2019. This date does not exist; there were only 28 days in February last year. Instead Calendar picks the day after February 28, that is, March 1. Causing you to get an incorrect month.
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.

Calendar.setTimeInMillis error - why is that? [duplicate]

This question already has answers here:
Java: Date from unix timestamp
(11 answers)
Closed 3 years ago.
calendar gets wrong unix time as I got.
long millis = 1568814839L;
System.out.println(millis); //1568814839
Calendar.getInstance(TimeZone.getTimeZone("Asia/Tashkent"));
calendar.setTimeInMillis(millis);
System.out.println(calendar.get(Calendar.MILLISECOND));//839
What should I do? Calendar.YEAR should be 2019 with that millis. However, calendar gives me 1970, why?
The error is due to you confusing time in milliseconds and time in seconds. 1568814839L is the number of seconds since 1/1/1970, but you're treating it as milliseconds. This is quite easy to check:
long millis = 1568814839L;
System.out.println(millis); //1568814839
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tashkent"));
System.out.println(calendar.getTimeInMillis()); //1568820981321
calendar.setTimeInMillis(millis);
System.out.println(calendar.get(Calendar.YEAR));//839
This will produce:
1568814839
1568820981321
1970
As you can see, your number is 3 orders of magnitude off. Add three 0's to the end of your millis number:
long millis = 1568814839000L;
...
System.out.println(calendar.get(Calendar.YEAR));
Now you get:
1568814839000
1568821211006
2019
java.time
The modern code would use java.time, the modern Java date and time API.
Feed your count of whole seconds since 1970-01-01T00:00Z to the Instant class:
ZonedDateTime zdt = Instant.ofEpochSecond(1_568_814_839L)
.atZone(ZoneId.of("Asia/Tashkent"));
System.out.println(zdt);
System.out.println("Year: " + zdt.getYear());
System.out.println("Millisecond of second: "
+ zdt.get(ChronoField.MILLI_OF_SECOND));
Output is:
2019-09-18T18:53:59+05:00[Asia/Tashkent]
Year: 2019
Millisecond of second: 0
As others have said, your number is seconds since the epoch, not milliseconds.
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.

How to get time entered by user in EditText and deduct 5 hrs 30 minutes from it?

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

Convert "using excel method" numeric value in date - java

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.

DateTime("2019-02-16T10:00:00+08:00") conversion to local date time with offset value

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

Categories

Resources