Android: Gregorian Calendar issue - java

I am getting confuse with using Gregorian.
I am using GregorianCalendar to get the current date and setting the future date.
The current month : it prints me the month as 8 rather 9 where 9 is my expected month.
The current year : it prints me the year in 2011 which is correct.
What is going wrong.
The code I use is GregorianCalender.getInstance(); to get the current date.

Using the jdk's calendar is a little confusing and you'll have to write a lot of code. Instead try a library called joda -
http://joda-time.sourceforge.net/

Related

Set date to specific date in Java every month and week [duplicate]

This question already has answers here:
Get first date of current month in java
(11 answers)
Closed 1 year ago.
Im working on a project that visually displays statistical data from each month and week and i dont know how to elegantly renew the dates of each week and month.
For example, i want to display this months data. I have to make two date variables in Java. The first one being 1.5.2021 and the second one being todays date. I dont know how to elegantly set the first variable to 1.x.xxxx without making a string out of the current date first and then cuting it, doing some numerics with it and merging it back together to 1.5.2021.
Same goes for weekly statistics where i need the Monday date and the Sunday date, for example today being Monday 10.5.2021 and the end on 17.5.2021.
So my idea is to get current date to string format, slice it, convert it to int, calculate the desired dates and the put it back to string(no need to go back to datetype since its gonna be used for querying).
Well, you should definitely take a look at the classes within the java.time package.
In your case, your current date could be a LocalDate instance, for example with the following line:
LocalDate.of(2021, 5, 1);
And then you could just use the withDayOfMonth method to get a new LocalDate instance with the day of the month set to 1:
LocalDate currentDate = LocalDate.now();
LocalDate firstOfMonth = currentDate.withDayOfMonth(1);

Calling getTime changes Calendar value

I'm trying to get the sunday of the same week as a given date.
During this I ran into this problem:
Calendar calendar = Calendar.getInstance(Locale.GERMANY);
calendar.set(2017, 11, 11);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(calendar.getTime().toString());
results in "Sun Jan 07 11:18:42 CET 2018"
but
Calendar calendar2 = Calendar.getInstance(Locale.GERMANY);
calendar2.set(2017, 11, 11);
calendar2.getTime();
calendar2.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(calendar2.getTime().toString());
gives me the correct Date "Sun Dec 17 11:18:42 CET 2017"
Can someone explain why the first exmple is behaving this way? Is this really intended?
Thanks
Basically, the Calendar API is horrible, and should be avoided. It's not documented terribly clearly, but I think I see where it's going, and it's behaving as intended in this situation. By that I mean it's following the intention of the API authors, not the intention of you or anyone reading your code...
From the documentation:
The calendar field values can be set by calling the set methods. Any field values set in a Calendar will not be interpreted until it needs to calculate its time value (milliseconds from the Epoch) or values of the calendar fields. Calling the get, getTimeInMillis, getTime, add and roll involves such calculation.
And then:
When computing a date and time from the calendar fields, there may be insufficient information for the computation (such as only year and month with no day of month), or there may be inconsistent information (such as Tuesday, July 15, 1996 (Gregorian) -- July 15, 1996 is actually a Monday). Calendar will resolve calendar field values to determine the date and time in the following way.
If there is any conflict in calendar field values, Calendar gives priorities to calendar fields that have been set more recently. The following are the default combinations of the calendar fields. The most recent combination, as determined by the most recently set single field, will be used.
For the date fields:
YEAR + MONTH + DAY_OF_MONTH
YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
YEAR + DAY_OF_YEAR
YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
In the first example, the fact that the last field set was "day of week" means it will then use the YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK calculation (I think). The year and month have been set to December 2017, but the week-of-month is the current week-of-month, which is the week 5 of January 2018... so when you then say to set the day of week to Sunday, it's finding the Sunday in the "week 5" of December 2017. December only had 4 weeks, so it's effectively rolling it forward... I think. It's all messy and you shouldn't have to think about that, basically.
In the second example, calling getTime() "locks in" the year/month/day you've specified, and computes the other fields. When you set the day of week, that's then adjusting it within the existing computed fields.
Basically, avoid this API as far as you possibly can. Use java.time, which is a far cleaner date/time API.
As Jon Skeet said, avoid Calendar. For your case it is truly horrible, and it’s poorly designed in general. Instead do
WeekFields weekFieldsForLocale = WeekFields.of(Locale.GERMANY);
// To find out which number Sunday has in the locale,
// grab any Sunday and get its weekFieldsForLocale.dayOfWeek()
int dayNumberOfSundayInLocale = LocalDate.now()
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY))
.get(weekFieldsForLocale.dayOfWeek());
LocalDate date = LocalDate.of(2017, Month.DECEMBER, 11);
LocalDate sunday
= date.with(weekFieldsForLocale.dayOfWeek(), dayNumberOfSundayInLocale);
System.out.println(sunday);
This prints the expected date
2017-12-17
As others have already mentioned, the solution is to use java.time, the modern Java date and time API. Also generally it is so much nicer to work with. One nice feature is the LocalDate class that I am using. It is a date without time of day, which seems to match your requirements more precisely that Calendar did.
If the above looks complicated, it’s because, as I think you are aware, “Sunday of the same week” means different things in different locales. In the international standard that Germany follows, weeks begin on Monday, so Sunday is the last day of the week. In the American standard, for example, Sunday os the first day of the week. WeekFields.dayOfWeek() numbers the days of the week from 1 to 7, so when we want to set the day to Sunday, we first need to find out which number Sunday has got in this numbering (7 in Germany, 1 in the US). So for any Sunday, get its weekFieldsForLocale.dayOfWeek() value and later use this for setting the day of week to Sunday. The reason why this is necessary is that the with() method is so general and therefore has been designed to accept only numeric values; we can’t just pass it a DayOfWeek object.
If I substitute Locale.US into the code, I get 2017-12-10, which is the correct Sunday for a calendar where Sunday is the first day of the week. If you are sure your only want your code to work for Germany, you may of course just hardcode a 7 (please make it a constant with a very explanatory name).
Link: Oracle Tutorial Date Time explaining how to use java.time. There are other resources on the net (just avoid the outdated placed that suggest java.util.Calendar :-)

Getting wrong date when I add months

I am writing my stubs in StubbyDB. And asserting the data in functional tests. This is something I am doing in my functional tests to calculate date for assertion (using joda datetime library)
DateTime now = DateTime.now();
DateTime future = now.plusMonths(6);
And this is something I am doing in my stubs;
{{TODAY+6m}}
But I am getting the difference of few days. Is this the bug or am I doing something wrong?
Edit
Consider today is "30 Sept 2016", and I add 5 months to it then
now.plusMonths(5) => 2017-02-28
{{TODAY+5m}} => 2017-03-02
Reason
As per joda-time documentation,
2007-03-31 plus one month cannot result in 2007-04-31, so the day of
month is adjusted to 2007-04-30.
However StubbyDB use javascript based date calculation which adjust date 2007-04-31 to 2007-05-01.
So this is not the bug but this is how these APIs work.
Solution
Found in sample application
use {{JODA_TODAY+6m}} instead of {{TODAY+6m}}
if you start with 30/09/2016 and add five months you get 30/02/2017.
But February only has 28 days.
It looks like Jodatime has "rounded down" to give you the maximum valid date for the month (i.e 28th Feb) whereas the other library/code is treating "30th Feb" as 2nd March (since that is technically two days past the 28th, which the 30th would also be).
Both are valid assumptions for handling dates IMHO and are a good lesson in why date handling is hard. You'll need to be explicit about which convention you want to follow and you may have to code your assertions to follow Jodatime's conventions.
See: DateTime::plusMonths(int)
Returns a copy of this datetime plus the specified number of months.
The calculation will do its best to only change the month field
retaining the same day of month. However, in certain circumstances, it
may be necessary to alter smaller fields. For example, 2007-03-31 plus
one month cannot result in 2007-04-31, so the day of month is adjusted
to 2007-04-30.
So, 30 Sept 2016 + 5 months = 28 Feb 2017 (according to Joda's logic) and it is not a bug
Here is sample code for adding months to given calendar date
public class Demo {
// create a calendar
Calendar cal = Calendar.getInstance()
// print current date
System.out.println("The current date is : " + cal.getTime());
// add 1 months from the calendar
cal.add(Calendar.MONTH, 1);
}
FYR How to add one month to a date and get the same day

Java check if date is next sunday

I get a date and want to check if it is the next sunday.I found alot of code with Calendar etc, but I can't find the right code. And I don't really understand how I can know if it is the next sunday from a date.
Thanks for you help
Break the problem down:
Get today's date: new Date();
Get the day of the week for today's date.
Advance forward to Sunday
Get that date
First of, I recommend Joda Time as a much better Date/Time API than Calendar.
As for your processing it breaks down into easy steps:
Construct DateTime objects for the two dates
Check that the target date is a Sunday
Check that the difference between them is between 0 and 7 days
If you look for nice Date management, check this out Joda Time
this might be helpful to you , you can chek by dayOfWeek == Calendar.SUNDAY after adding one day
With Lamma Date it's very easy to first obtain next Sunday, then we can use equals check if the date is next Sunday.
Date today = new Date(2014, 7, 1); // assume today is 2014-07-01
Date nextSunday = today.next(DayOfWeek.SUNDAY); // 2014-07-06

how to detect day light saving in java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get the current date and time of your timezone in Java?
I have developed a Attendance System and in use for India. Our servers are in US and since they are using PDT. My code reflects time one hour ahead.
say its 9:00 am IST ---- I get the time as 10:00 am IST
other than detecting one hour from the time, which will be a temporary solution.
Pls suggest me some way to overcome this situation
To check if a given Date is affected by daylight saving, use
Calendar c = Calendar.getInstance(timezone); // omit timezone for default tz
c.setTime(date); // your date; omit this line for current date
int offset = c.get(Calendar.DST_OFFSET);
0 means no DST, any other value (most likely 3600000) means that this date is affected by DST

Categories

Resources