Java - GregorianCalendar outputting wrong year? - java

When I instantiate a new date using GregorianCalendar like this:
GregorianCalendar myCal = new GregorianCalendar(29,5,2011);
Then, finally, I carry out the following code (expecting it to return 2011), and it returns 35. I'm wondering why this is, as I will need to compare it to the passed date (2011).
System.out.println(myCal.get(Calendar.YEAR));

Are you even reading the documentation/method signatures?
public GregorianCalendar(int year, int month, int dayOfMonth)
Try this:
GregorianCalendar myCal = new GregorianCalendar(2011, Calendar.MAY, 29);
And BTW: 5th month is actually June, I guess you wanted May (months are 0-based). To avoid confusion use constants like Calendar.MAY (equal to 4...)

The GregorianCalendar constructor you are using does not expect dayOfMonth, month, year as arguments, but year, month, dayOfMonth. See the JavaDoc for details.

Related

Java: How can I create method that works on my date class

I have a date class and it has the following
public class Date {
public int month;
public int day;
public int year;
public Date(int m, int d, int y)
{
month = m;
day = d;
year = y;
}
public Date increase(int numberOfDays)
{
day += numberOfDays;
return this;
}
My question is what is the easiest way to do increasing of number of days to that given instance of Date? Like for example I have a created an instance of new Date(4,20,2016).increase(30); which would increase the given date addition 30 days. That would be sometime in May 19 I think. The method above should work if it's less than the max day of the month. But I haven't figure out how to do the calculation including the month and year. Like I added 365 days to that date would be 4/20/2017. Just an idea would be helpful. Thanks
use Java Calendar object instead. https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 30); // add 30 days
date = cal.getTime();
using jcalendar you can add the dates try this example
Implementing this yourself is a suprisingly tricky task. More so since you are storing your Date as a separate month, year and day. You would have to store information about the number of days in every month, along with information about leap years. In short, trying to re-implement Date is not easy.
One solution to storing a "day, month, year" date before Java 8 came along was to use Joda. Using Joda's LocalDate class, you can do:
LocalDate date = LocalDate.now();
date = date.plusDays(30);
This functionality is now available in Java 8's java.time package, using the same LocalDate class name. Take a look at the source code for either package to see how it's implemented.
In short, LocalDate.plusDays() first converts the "month, day, year" date to a single number of days since the "epoch", using an algorithm that's around twenty lines long. Then, it adds the requested number of days to that number. Finally, it converts that number back to a "day, month, year" using another algorithm that's even longer.

Finding out what day the first of any given month is

So I need to make a basic calendar which displays the calendar for a specific year and month (the user should be able to select
any month and any year based on text input).
So far, I have managed to create a calender obj, use Scanner to get the desired month and year from the user but my question is that how do I find out what the first day of the month is? In the example above, it's a Saturday. My logic to building it is that if I know the first day, I can make a String[][] array and start displaying the day on the relevant date by looping through the month from the first day. I've used a scanner to get the required month and year. I then created a calendar object and set the Calendar variables; Calendar.YEAR and Calendar.MONTH, as per required by the user:
Calendar cal= Calendar.getInstance();
cal.set(Calendar.YEAR, year); //my year variable is set 2015
cal.set(Calendar.MONTH, chosenMonth); //my chosenMonth is set to 5 since January starts from 0.
I tried using the following code to test out my calender to see if it will execute the code if Monday was the first day of the month. On june 2015, it was.
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY){
System.out.println("This will print is my calendar secessfully gathers that monday was the first day of the month on June 2015.")
}
It doesn't execute.
Try this:
cal.set(Calendar.DATE, 1);
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEEE");
System.out.println(sdf.format(cal.getTime()));
Output:
Saturday
Demo
Java SE 8 has a whole new API for date and time, java.time. See Tutorial.
You can use the class LocalDate to get the day of a given week. For example, using your day from above do,
LocalDate d = LocalDate.of(2011, 10, 1);
Then LocalDate::getDayOfWeek() method will return a DayOfWeek enum instance, such as SATURDAY.
DayOfWeek dayOfWeek = localDate.getDayOfWeek ();
That enum can render a localized string for your sentence output.
String output = dayOfWeek.getDisplayName ( TextStyle.FULL , Locale.CANADA_FRENCH); // Or Locale.US or Locale.ENGLISH, and so on.
samedi

Statically created dates are not equal?

I'm testing the equality of dates that I create using constants and for some reason the tests are all failing.
public static Date date(int year, int month, int date, int hour, int minute) {
Calendar working = GregorianCalendar.getInstance();
working.set(year, month, date, hour, minute, 1);
return working.getTime();
}
If I create that with the same year, month, date, hour etc then I expect it to be equal. Except that it inconsistantly isn't. I use this function in two different classes and the objects aren't equal - except only sometimes.
What's the issue? The epoch it gives me is occasionally 1 second behind the other and I'm not entirely sure why.
getTime is millisecond precision, you are only setting to second precision. So when you compare the Dates using the .equals() method it will return false.
Stop using the abomination of the java date time api and use jodatime instead.
DateTime dateTime = new DateTime().secOfDay().roundFloorCopy();
dateTime.equals(myOtherDateTimeCreatedSameway);
Or if you are just worried about date, not time, use LocalDate.
The old calendar-API is undoubtedly horrible in general but I show a possible solution which suppresses the millisecond part generated in constructor. This will work as long as you don't change the timezone. So sometimes the Calendar-API is underestimated while JodaTime is often overestimated.
public static Date date(int year, int month, int date, int hour, int minute) {
// current time in system timezone
GregorianCalendar working = new GregorianCalendar();
// assuming you rather want second set to zero
working.set(year, month, date, hour, minute, 0);
// no millisecond part
working.set(Calendar.MILLISECOND, 0);
return working.getTime();
}

Android get difference in milliseconds between two dates

I have Integer fields:
currentYear,currentMonth,currentDay,currentHour,currentMinute and nextYear,nextMonth,nextDay,nextHour,nextMinute.
How I can get difference between those two spots in time in milliseconds.
I found a way using Date() object, but those functions seems to be depricated, so it's little risky.
Any other way?
Use GregorianCalendar to create the date, and take the diff as you otherwise would.
GregorianCalendar currentDay=new GregorianCalendar (currentYear,currentMonth,currentDay,currentHour,currentMinute,0);
GregorianCalendar nextDay=new GregorianCalendar (nextYear,nextMonth,nextDay,nextHour,nextMinute,0);
diff_in_ms=nextDay. getTimeInMillis()-currentDay. getTimeInMillis();
Create a Calendar object for currenDay and nextDay, turn them into longs, then subtract. For example:
Calendar currentDate = Calendar.getInstance();
Calendar.set(Calendar.MONTH, currentMonth - 1); // January is 0, Feb is 1, etc.
Calendar.set(Calendar.DATE, currentDay);
// set the year, hour, minute, second, and millisecond
long currentDateInMillis = currentDate.getTimeInMillis();
Calendar nextDate = Calendar.getInstance();
// set the month, date, year, hour, minute, second, and millisecond
long nextDateInMillis = nextDate.getTimeInMillis();
return nextDateInMillis - currentDateInMillis; // this is what you want
If you don't like the confusion around the Calendar class, you can check out the Joda time library.

Ambiguous result date java

i'm retrieving a strange result:
First i get current date using GregorianCalendar:
GregorianCalendar g = new GregorianCalendar();
int m = g.get(Calendar.DAY_OF_MONTH);
int d = g.get(Calendar.DAY_OF_WEEK);
int y = g.get(Calendar.YEAR);
Then i create new object Date:
Date d = new Date(d,m,y);
Then i print them together in this way:
System.out.println(d+" - "+m+" - "+y+" - "+d);
and i get:
1 - 18 - 2012 - Thu Jan 02 00:00:00 CET 1908
can you explain me why? is for deprecated method Date(day,mouth,year) ?
if yes, how can i compare two Date using that parameters?
Then i create new object Date:
Date d = new Date(d,m,y);
The order of the arguments to the constructor is year, month, date, nothing else.
From the documentation:
Date(int year, int month, int day)
how can i compare two Date using that parameters?
Depends on how you want to compare two Dates. If you just want to figure out which comes first, you could use Date.before and Date.after.
But as you've noted, the Date class is deprecated. Use the Calendar class instead, (or better yet, the Joda Time library)
If you need to obtain a new Date object from a GregorianCalendar, do this:
Date d = g.getTime();
In this way, you won't have to use deprecated methods, and the result will be the one you expect. Also, if you need to obtain the current date, simply write new Date(), no need for a GregorianCalendar.
As far as date comparisons go, you can use Date's compareTo(), after() and before() methods. Again, there's no need for a GregorianCalendar.
Create a Calendar, then set the time using the Date object, then you can get any information you need from it.
Example:
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int day = cal.get(Calendar.DAY_OF_MONTH);
// and so on....

Categories