Require help for SWT DateTime in Java - java

I retrieve a Date from the database using the ResultSet rsExpid.
Date joindate = rsExpid.getDate("join_date_ad");
System.out.println(joindate);
int year = joindate.getYear();
System.out.println(year);
int month =joindate.getMonth();
System.out.println(month);
int day = joindate.getDay();
System.out.println(day);
dateTimeJoin4.setDate(year, month, day);
When I print joindate to the console it shows correctly as 2011-08-03, but when I print the year to the console I was amazed to see 111. Similarly printing the month produced 7 and the day resulted in 3.
The variable dateTimeJoin4 is my SWT DateTime. It is not setting any value and it is also not giving any error message. Could please anybody help me on this?

Chances are you haven't read the documentation for Date.getYear and Date.getMonth:
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
and
Returns a number representing the month that contains or begins with the instant in time represented by this Date object. The value returned is between 0 and 11, with the value 0 representing January.
respectively. Likewise Date.getDay returns the day of the week, not the day of the month - you want Date.getDate() for that (or preferrably a different API entirely, either Calendar or Joda Time).
This has nothing to do with SWT's DateTime type - after all, you only use that in the last line. When something behaves unusually, your first port of call should be the documentation. SWT's DateTime.setDate method is documented to require a year between 1752 and 9999, so 111 will be confusing it. Admittedly it would have been nice if it had thrown an exception, but even so...
The fact that you're calling deprecated methods should have been a hint to you, although Calendar also uses 0-11 for its months.
Personally I would strongly encourage you to use Joda Time for as much of your date and time work as you can. It's a far superior date and time API to the one built into Java. It's not immediately clear whether it's worth you using it here (if this is all you have to do) but if you're doing anything at all significant (including parsing, formatting or any kind of arithmetic) you should be using it.

I tried using this method and it worked correctly so this method can be useful to other.
Calendar startCal = Calendar.getInstance();
startCal.setTime(joindate);
int months= startCal.get(Calendar.MONTH);
int years= startCal.get(Calendar.YEAR);
int days= startCal.get(Calendar.DAY_OF_MONTH);
System.out.println(months+1);
System.out.println(years);
System.out.println(days);
dateTimeJoin4.setDate(years, months+1, days);

getDay() return the position of the day not the date like suppose today is Monday it will return 1, it start from the sunday with 0 value.
as well as the getMonth() return the position as starting value is 0 for january at now you getting the 7 instead of 8.
for getting date you can use the SimpleDateFormat or DateFormat by passing the format string in that you can get it
example links
http://www.roseindia.net/java/javadate/date-format.shtml
http://www.java-examples.com/java-simpledateformat-class-example

Related

Get Day, Month, Year from Java Calendar instance

I have an Instant derived from a Java Calendar, e.g. c.toInstant(), and now in a different location convert that to a custom Date object that needs a day of the month, month, and year. I tried:
if (instance.isSupported(ChronoField.DAY_OF_MONTH) && instance.isSupported(ChronoField.MONTH_OF_YEAR) && instance.isSupported(ChronoField.YEAR)) {
return new com.company.common.Date()
.setDay(instance.get(ChronoField.DAY_OF_MONTH))
.setMonth(instance.get(ChronoField.MONTH_OF_YEAR))
.setYear(instance.get(ChronoField.YEAR));
}
But when I try to compile ErrorProne throws:
...impl/utils/DateUtils.java:21: error: [TemporalAccessorGetChronoField] TemporalAccessor.get() only works for certain values of ChronoField.
.setDay(instance.get(ChronoField.DAY_OF_MONTH))
^
I'm not sure why I can't find an answer for this anywhere, but after some searching I came up with nothing helpful -- though I probably missed something.
Instant is only a timestamp - it only provides seconds, millis and nanos.
If you start with a Calendar instance in the first place you should be able to simply use
calendar.get(Calendar.YEAR)
calendar.get(Calendar.MONTH) + 1
calendar.get(Calendar.DAY_OF_MONTH)
directly to fetch the date values and skip the conversion to Instant.
Note that in Calendar month is a zero-based value. You usually have to add one to get to value one would commonly expect.
If you prefer working with the newer time API you can fetch dates and time from a ZonedDateTime like
Calendar calendar = Calendar.getInstance();
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId());
zonedDateTime.getYear();
zonedDateTime.getMonthValue();
zonedDateTime.getDayOfMonth();
I don't see a direct advantage for the example given, beyond getting the "correct" value for month here directly.
It could be useful if you want to do any additional work with the date value beyond just reading its contents.
Generally speaking ZonedDateTime and all other types from the java.time package provide the more robust API and functionality compared to the older Calendar type. Therefore avoid the calendar type for any new code

GegorianCalendar is giving me 2018 for int month = calendar.get(Calendar.FEBUARY)

So Im working on an Calendar programm and to change the Months im asking for the int of the month.
If I type calendar.get(Calendar.JANUARY) i get 1 as return, which is correct because first month. But if I type calendar.get(Calendar.FEBUARY) i get 2018 in respond which of course is wrong. Does anyone know what the problem could be?
Calendar cal1 = new GregorianCalendar();
int month = cal1.get(Calendar.JANUARY);
int month2 = cal1.get(Calendar.FEBRUARY);
int year = cal1.get(Calendar.YEAR);
java.time
T.J. Crowder’s answer is correct. Allow me to supply the real, good and modern solution to your problem.
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Atlantic/Stanley"));
// 2018-05-21T05:02:23.942763-03:00[Atlantic/Stanley]
Month monthEnum = zdt.getMonth(); // MAY
int monthNumber = zdt.getMonthValue(); // 5
int year = zdt.getYear(); // 2018
I ran the code just now and have given results in comments after each code line. Please put your desired time zone where I have put Atlantic/Stanley since the month does not change at the same point in time in different time zones. Do you agree with me that this code is clearer and more natural and leaves less room for confusion? BTW, if you’re only interested in the date, not the time of day, use LocalDate instead of ZonedDateTime, the rest of the code will be the same.
To get the numbers of specific months:
int januaryNumber = Month.JANUARY.getValue(); // 1
int februaryNumber = Month.FEBRUARY.getValue(); // 2
What happened in your code?
As T.J. Crowder has already said, Calendar.get expects a field number, for example Calendar.MONTH or Calendar.YEAR. Calendar.JANUARY is 0. Zero?! It’s another confusing thing about Calendar, month numbers are 0-based, that is, they go from 0 for January through 11 for December. Anyway, 0 is also the field number of Calendar.ERA. GregorianCalendar uses 0 for BC (or more religion neutral: BCE for before common era) and 1 for AD (CE, common era). Since your date is in the common era, you get 1. Which, by the way, would have been incorrect for month of January since months are 0-based.
Similarly, Calendar.FEBRUARY equals 1 and coincides with field number Calendar.YEAR, which I why you got the year.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Question: Why is January month 0 in Java Calendar?
Calendar#get gets a field value. Calendar.JANUARY is not a field number, it's a potential field value. The only static fields in Calendar that you use with get (and set) are the ones whose descriptions start with "Field number for get and set...".
To get the month, use cal1.get(Calendar.MONTH).
The Calendar API is...unfortunate, not least because it predates enums and so int was used for get/set's field identifier parameter where an enum was really needed. While get takes an int, and Calendar.JANUARY is an int, they're ints in different domains. See Ole V.V.'s answer for the modern, dramatically-improved alternative: java.time.

Why is this Scala code to retrieve the current year returning "113"?

val year=Calendar.getInstance().getTime().getYear().toString
I am not getting the correct year. It is giving 113 if the year is 2013, but I want to get 2013.
Perhaps this Java code will work better for you:
int year=Calendar.getInstance().get(Calendar.YEAR);
If you have Java 8, you could also try:
int year=Year.now().getValue();
This is not Scala specific as you noted with your scala tag, you are using the java.util.Date getYear() method which is deprecated and
Returns a value that is the result of subtracting 1900 from the year
that contains or begins with the instant in time represented by this
Date object, as interpreted in the local time zone

Calendar.getTime().getYear() gives back 0113 instead of 2013

I'm making a little game. When the game is starting for the first time i saves the time since 01.01.1970 in seconds in the SharedPreferences.
Now i want to give this date out on my screen in this form: DD.MM.YYYYY
I used the Calendar function but it give back 02.04.0113 so, there are missing 1900 Years.
Here is my Code:
private void initBornTXT() {
SharedPreferences pref = getSharedPreferences("LIFE", 0);
long born = pref.getLong("BIRTHDAY", 0);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(0);
c.add(Calendar.SECOND, (int)born);
int year = c.getTime().getYear();
int month = c.getTime().getMonth();
int day = c.getTime().getDay();
String string_born = String.format("%02d.%02d.%04d", day, month, year);
TextView born_txt = (TextView)findViewById(R.id.textViewBorn);
born_txt.setText(string_born);
}
What coud be wrong?
Nothing's wrong. You've just not looked at the documentation for the method you're calling, Date.getYear():
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
Note that you should have received a warning that you're using a deprecated API: don't just ignore those warnings.
Also, do yourself a favour and don't do the formatting yourself: use SimpleDateFormat instead. (Or ideally, use Joda Time instead...) That way you can avoid the month being wrong, too... you may not have noticed that you're a month off due to months being 0-based, which is common to both Calendar and Date.
That's normal, documented behavior. See JavaDoc for Date#getYear().
A better way to get the year would be:
c.get(Calendar.YEAR)
You're using getTime, which returns a date object. Dates are based on 0=1900. So this is the expected output. Use a SimpleDateFormat instead.
Kudos for creating a Y2K bug though :)

Help with Java Calendar -- it is giving some strange output

I'm newish to Java and am trying to do somethings with dates. First I started using the Date class, which I found out was mostly deprecated so I switched over to Calendar.
Now I am getting weird values. for example the Month value for December is 0, not 12. And on those Calendars where it is giving me 0 for December it is also moving the year ahead one year.
It's weird!
What am I missing?
Thanks for your help.
-GG
EDIT FOR AN EXAMPLE:
So I am reading some line sin from a file such as this:
Johnny Graham H F 12-2-1973 Black
I parse it, and then for the Calendar I set:
int year = Integer.parseInt(stringVersionOfYear); // this value is 1973
Then later when I go to get the year back with a line like this:
calendar.get(Calendar.YEAR)
the value is 1974... And the month is 0 for
cal.get(Calendar.MONTH)
EDIT 2:
I am creating the Calendar like this:
Calendar outputCalendar = Calendar.getInstance();
outputCalendar.set(year, month, day);
The java.util.Date and Calendar classes are poorly designed (eg, the first day in a month is day 1 but the first month in a year is month 0). Many projects use the Joda Time package instead.
Months values are 0 thru 11; set a month to 12 and the date gets "normalized", incrementing the year by one and setting the month to 0. This makes it easy to "add a month" without having to worry about handling the overflow at year end.
EDIT: January=0, February=1,... December=11. When you set the month value to 12 you were asking for the 13th month, which got normalized to the first month of the following year.
Note that this normalization process happens in general -- Try to set the date to December 32nd and you'll get back January 1 of the following year. This means it's important to be careful when modifying individual fields of a Calendar object. If you create a default Calendar on, say, January 31st and then want to modify it to contain, say February 5th, the order in which you set the fields is important. If you change the month first you'll be creating February 31st, which will get normalized to March 2nd or 3rd (depending on the leap year) and then when you set the day to 5 the result is March 5th, not February 5th. You have the opposite problem in other cases, such as starting from any date in February and modifying to the 30th or 31st of any other month. In that case doing the month first results in the same type of problem.
The only safe way to modify a date is to use a method that sets all three values simultaneously, such as the set(int,int,int) method.
See this line?
outputCalendar.set(year, month, day);
Just change it like this:
outputCalendar.set(year, month - 1, day);
and then when you want to get the month, don't use this:
cal.get(Calendar.MONTH)
instead, use this:
(1+(cal.get(Calendar.MONTH)))
It's a pain, but it will fix the problem (I think).
The main piece of advice I have for you is: read the API! Calendar is indeed not the pinnacle of intuitive API design, but it is definitely usable if you take the time to read the javadoc. Learn the difference between .add and .roll. Check out what happens when you set a year (1973) into a Calendar initialized with the current date (default Calendar.getInstance).
Whining about API is all fine (we all do it), but in the end to find solutions start off by reading what the authors provided to you before asking relatively obtuse questions on the Internet.

Categories