Java Calendar always shows the same time - java

Below is my code.
public class TestCalendar {
public static void main(String[] args){
int unique_id = Integer.parseInt("" + Calendar.HOUR + Calendar.MINUTE
+ Calendar.SECOND);
System.out.println(unique_id);
}
}
Calendar.HOUR is supposed to give me
public static final int HOUR Field number for get and set indicating the hour of the morning or
afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not
by 12. E.g., at 10:04:15.250 PM the HOUR is 10.
It doesnt matter how many times I run this code, it always gives me the same unique_id. (101213) and my local time on my machine is 1:30pm. What am I doing wrong here?
Thanks.

Your code is just concatenating constants, that the Calendar defines to identify some of it's fields. To get values of these fields, call Calendar.get() and pass the constant identifier as an argument:
public class TestCalendar {
public static void main(String[] args){
Calendar c = Calendar.getInstance();
int unique_id = Integer.parseInt("" + c.get(Calendar.HOUR) + c.get(Calendar.MINUTE)
+ c.get(Calendar.SECOND));
System.out.println(unique_id);
}
}
The above would work, but the result will be far from unique ID.
To get an ID uniquely identifying a point in time (with the precision of milliseconds), consider Calendar.getTimeInMillis().

Calendar.HOUR, Calendar.MINUTE and Calendar.SECOND are public static int field of the Calendar class. Their value is
CALENDAR.HOUR: 10
CALENDAR.MINUTE: 12 and
CALENDAR.SECOND: 13.
Your String concatenation is just appending this values. To read from a Calendar you could so something similar to
calendar.get(Calendar.HOUR);
calendar.get(Calendar.MINUTE);

I am not sure what is requirement but if you want system time then may be you can use this "System.currentTimeMillis()"

Calendar.HOUR (or MINUTE, SECOND) is just an indicator that indicates which field we want to extract from the Calendar instance, not the value, i.e. we want to 'extract HOUR from the calendar object' like below:
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY); // in 24-hours,
// or c.get(Calendar.HOUR) in 12-hours.
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
int weekday = c.get(Calendar.DAY_OF_WEEK);
int weekOfYear = c.get(Calendar.WEEK_OF_YEAR);

For those who are still having some problems with this, like I did, especially when you want to print multiple times you may need to to use new like follows:
System.out.println(""+new GregorianCalendar().get(Calendar.HOUR_OF_DAY)+":"+new GregorianCalendar().get(Calendar.MINUTE)+":"+new GregorianCalendar().get(Calendar.SECOND)+":"+new GregorianCalendar().get(Calendar.MILLISECOND));

Related

Calendar.set not changing Calendar variables

I've been working on a program for my Computer Programming class and I'm having a little trouble. Truthfully, I'm on the verge of insanity...
Its a calendar program and the part I'm having trouble with is the Calendar object in java. Here is my code for one of methods:
public static void calendarGet(){
String md = getInput("What date would you like to look at?(mm/dd)");
int slash = md.indexOf('/');
MDFromDate(md);
cal.set(cal.MONTH, MONTH - 1);
cal.set(cal.DATE, DAY);
TARGET_DAY = DAY;
MAX_DAY = cal.getActualMaximum(cal.DAY_OF_MONTH);
WEEKS_IN_MONTH = MAX_DAY / 7;
System.out.println(cal.MONTH + 1);
System.out.println(cal.DAY_OF_MONTH);
System.out.println(cal.getTime());
drawMonth(cal.MONTH);
}
And the output for this is:
What date would you like to look at?(mm/dd)12/12
3
5
Wed Dec 12 22:47:32 PST 2018
As you can see, if I use getTime(); it returns the right month and day but cal.MONTH and cal.DAY_OF_MONTH do not.
Also, when I use the debugger and look in cal, none of the variables had changed.
I'm incredibly confused, I would appreciate some help! :D
EDIT:
public static String getInput(String prompt){
System.out.print(prompt);
Scanner inScan = new Scanner(System.in);
return inScan.nextLine();
}
public static void MDFromDate(String md){
Scanner getMD = new Scanner(md).useDelimiter("/");
MONTH = getMD.nextInt();
DAY = getMD.nextInt();
}
So...
System.out.println(cal.MONTH + 1);
System.out.println(cal.DAY_OF_MONTH);
is printing the constant values assigned to Calendar.MONTH and Calendar.DAY_OF_MONTH, this are not the values contained within the Calendar instance, they are simply values you can use to set/get values of the Calendar
So, if instead we use Calendar#get, for example...
Calendar cal = Calendar.getInstance();
int month = 12;
int day = 12;
cal.set(cal.MONTH, month - 1);
cal.set(cal.DATE, day);
System.out.println(cal.get(Calendar.MONTH));
System.out.println(cal.get(Calendar.DATE));
It will print...
11
12
But wait, why 11, because the months are zero indexed (ie January is 0)
Part of the confusion is down to the fact that you're not using the standard coding conventions for the Java Language, which states variable names which all all uppercase (MONTH/DAY) are constants, which they aren't in your code
And, yes, as I'm sure some is bound to point out, you shouldn't be using Calendar but instead the newer java.time API, but if your teacher wants you to use it, who are we to contradict them :/
In a very well-explained answer MadProgrammer asks:
And, yes, as I'm sure some is bound to point out, you shouldn't be
using Calendar but instead the newer java.time API, but if your
teacher wants you to use it, who are we to contradict them :/
I am taking the chance. If only for other readers that are not under the same restrictions. Teachers are different. When I was teaching, I certainly appreciated whenever students found a different solution from what I had imagined. You know your teacher better, so I hope you know what is right in your situation, I certainly don’t.
private static final DateTimeFormatter monthDayFormatter
= DateTimeFormatter.ofPattern("M/d");
public static void calendarGet(){
String md = getInput("What date would you like to look at?(mm/dd)");
LocalDate date = MonthDay.parse(md, monthDayFormatter)
.atYear(Year.now(ZoneId.of("America/Los_Angeles")).getValue());
int targetDay = date.getDayOfMonth();
int maxDay = date.lengthOfMonth();
System.out.println(date.getMonth());
System.out.println(date.getDayOfMonth());
}
When I entered 04/05, this printed
APRIL
5
IMHO the code using java.time is clearer to read and what should be taught in schools.

Comparing Just the Date (not time)

I need to compare 2 dates to a third date and ignore the time portion of all of them.
The code below generates a parse exception because the toString() method returns something like "Wed Feb 26 00:00:00 EST 2014".
Any suggestions on how I might fix this?
private boolean needToSendEmail(EmSelfCertEntity escd) throws ParseException {
boolean sendEmail = false;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date justTheDate = df.parse(escd.getCurrentFCESDate().toString());
Calendar firstSent = Calendar.getInstance();
firstSent.setTime(justTheDate);
justTheDate = df.parse(new Date().toString());
Calendar firstFollowUp = Calendar.getInstance();
firstFollowUp.setTime(justTheDate);
firstFollowUp.add(Calendar.DATE, -daysToFirstFollowUpEmail);
Calendar secondFollowUp = Calendar.getInstance();
secondFollowUp.setTime(justTheDate);
secondFollowUp.add(Calendar.DATE, -daysToSecondFollowUpEmail);
if ((firstSent.before(firstFollowUp) && escd.countEmailsSent <= 1)
|| (firstSent.before(secondFollowUp) && escd.countEmailsSent <= 2)) {
sendEmail = true;
}
return sendEmail;
}
Thanks!
Why are you parsing the String when you already have the Date?
If you want to format your existing Date into the format you specified, use the format() method instead:
String justTheDate = df.format(new Date());
Then you can compare the Strings using the equals() method to check for matches.
Edit- By the way, if Java 8 is an option (it came out on Tuesday!), its new DateTime features will do exactly what you're looking for: http://docs.oracle.com/javase/tutorial/datetime/
The cause for your exception is that toString in escd.getCurrentFCESDate().toString()
delivers another format than "MM/dd/yyyy".
So make sure that either your format String in line SimpleDateFormat("MM/dd/yyyy") is correct.
Or check if you can get the year, month, and day directly from getCurrentFCESDate().
Just Use the calendar to create a date, where you take the year, months, day from the existing date but set the hours, minutes, seconds and millis to zero.
The result will be a Date object:
Something like
firstSent.set(Calendar.HOUR, 0);
firstSent.set(Calendar.MINUTE, 0);
firstSent.set(Calendar.SECOND, 0);
firstSent.set(Calendar.MILLISECOND, 0);
Then use before() and after()
The easiest approach would be to convert the dates to numbers in this format: yyyyMMdd.
And after that you can just compare the numbers.
But yes, please work with timezone adjustments before converting to numbers.
you can calculate the time in millis and substract the time with a simple / division.
This way you can compare 2 longs and check if one is bigger than another.
Take this example where we get to different dates for today (500 milliseconds from one to another) but... if you divide by 86400000 then... you get the same number.
Try this:
public static void main(String[] args) throws Exception {
Date d1= new Date();
Thread.sleep(500);
Date d2= new Date();
final int MILLISECONDS = 1000;
final int SECONDS = 60;
final int MINUTES = 60;
final int HOURS = 24;
final long MILLI_PER_DAY= MILLISECONDS*SECONDS*MINUTES*HOURS;
System.out.println(MILLI_PER_DAY);
System.out.println(d1.getTime());
System.out.println(d2.getTime());
System.out.println(d1.getTime()/MILLI_PER_DAY);
System.out.println(d2.getTime()/MILLI_PER_DAY);
}
You will see that the last 2 entries are the same:
1395338535623 --> time 1 in millis
1395338536123 --> time 2 in millis
16149 --> time 1 / 86400000
16149 --> time 2 / 86400000 --> THE SAME

How to write a method that returns number (int) of days from provided day to the todays date?

Please help me to write a method that returns number (int) of days from a provided day to the todays date.
So let's say, I am providing into a method an int 110515 (for May 15, 2011). It should return 9 (inclusive or exclusive is not important to me).
If you can use Joda, this is super simple:
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
Of course you could combine these.
int days = Days.daysBetween(startDate, endDate).getDays();
Joda objects can go back and forth between the JDK's date class pretty easily.
For the first part, make a DateFormatter then parse the string based on it, like this:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");
DateTime dt = fmt.parseDateTime(strInputDateTime);
(After turning the int into a string of course.)
Should dates in the future include the current day? Meaning if today is May 24th 2011, should 110529 result in 4 or 5?
public static long numberOfDays(final long date) throws ParseException {
final Calendar compare = Calendar.getInstance();
compare.setTime(new SimpleDateFormat("yyMMdd").parse(String.valueOf(date)));
final int dstOffset = compare.get(Calendar.DST_OFFSET);
final long currentTimeMillis = System.currentTimeMillis();
final long compareTimeInMillis = compare.getTimeInMillis();
long difference = 0;
if (currentTimeMillis >= compareTimeInMillis) {
difference = currentTimeMillis - compareTimeInMillis - dstOffset;
} else {
difference = compareTimeInMillis - currentTimeMillis + dstOffset;
}
return difference / (24 * 60 * 60 * 1000);
}
Since this seems like a homework question I will help you out. You will want to use Calendar.getTimeInMillis. Then you will want to create a constant that is NUMBER_OF_MILLIS_IN_DAY . From there you subtract the initialDate from the currentDate (both time in millis) and divide by the constant.

How do I determine time passed between two Calendar Objects in Java?

What is the best way to count the amount of time between two Calendar dates in java. I am writing a method that determines the number of months that pass between two dates and returns a boolean based on a predefined term of months. This is my code(does not work correctly).
This code always returns false. Also this code does not take into account the number of days passed. This could be a problem if the start date is at the end of a month. Is there not a simple compareTo method?
private boolean hasMatured()
{
Calendar now = Calendar.getInstance();
Calendar start = (Calendar) super.dateOpened.clone();
int nowYear = now.get(Calendar.YEAR);
int nowMonth = now.get(Calendar.MONTH);
int startYear = start.get(Calendar.YEAR);
int startMonth = start.get(Calendar.MONTH);
int monthsElapsed = (nowYear - startYear) * 12 + (nowMonth - startMonth);
return monthsElapsed>PERIOD_IN_MONTHS;
}
int nowYear = now.get(Calendar.YEAR);
int nowMonth = now.get(Calendar.MONTH);
int startYear = now.get(Calendar.YEAR);
int startMonth = now.get(Calendar.MONTH);
int monthsElapsed = (nowYear - startYear) * 12 + (nowMonth - startMonth);
I would strongly recommend Joda Time for all date-related stuff in Java. It has a much cleaner and more intuitive API, togather with the concepts of intervals between dates etc.
The code looks fine expect from one major caveat: Calendar is mutable.
So, instead of
Calendar start = super.dateOpened;
you should have done
Calendar start = (Calendar) super.dateOpened.clone();
otherwise the changes get reflected in dataOpened which may cause unexpected side-effects.
Am I missing something? There is a compareTo() in Calendar, as well as other useful stuff...
How about:
Calendar now = Calendar.getInstance();
now.add(Calendar.MONTH, -PERIOD_IN_MONTHS);
return super.dateOpened.before(now);
Subtract X months from today, and see if the start date is still before that date. If it is, then X months must have passed.

Stuck on testing a method

I am doing some table testing in word, all of the JUnits are done but i am having trouble testing a method - as i am the tester in this project and not the coder i am struggling to understand what is actually correct or not
public GregorianCalendar calcDeparture(String date, String time) {
String[] calDate = new String[3];
String[] calTime = new String[2];
calDate[0] = (date.substring(0, 2)); //Dat
calDate[1] = date.substring(2, 5); //Month
calDate[2] = "20" + date.substring(5, 7); //Year
calTime = time.split(":");
//Adds the year, month and day and hour and minute from the above splited arrays
int year = Integer.parseInt(calDate[2]);
int month = monthToInt(calDate[1]);
int day = Integer.parseInt(calDate[0]);
int hour = Integer.parseInt(calTime[0]);
int minute = Integer.parseInt(calTime[1]);
GregorianCalendar newDeparture = new GregorianCalendar(year, month, day, hour, minute, 0);
return newDeparture;
}
This is the method I am testing. If i pass it the values of "01AUG07 "14:40" i get a gregorian calander back but i don't know if the values inside of it are correct so i can't tick the passed or failed box. What i get back in the BlueJ object inspector is a load of really long numbers :D
can i get some help please
thanks
I suggest to check all the relevant values of the calendar at the same time using a SimpleDateFormat() like so:
SimpleDateFormat f = new SimpleDateFormat ("yyyy-MM-dd HH:mm");
String s = f.format (calcDeparture(yourDate, yourTime));
assertEquals ("2007-08-01 14:40", s);
Now call your method with odd dates (like 31.12.2999, August 45th, February 29th 2001, etc) to see what you get and how you should handle errors.
BlueJ? Consider using an IDE, not an educational software
The method is terribly written - working with dates using a strictly-formatted String is wrong.
Calendar (which is the supertype of GregorianCalendar) has the get method, which you can use like:
Calendar calendar = calcDeparture(yourDate, yourTime);
int day = calendar.get(Calendar.DAY_OF_YEAR);
int moth = calendar.get(Calendar.MONTH); //this is 0 based;
and so on
Why can you just not use the standard getters to check the individual fields, along the lines of:
Calendar cal = calcDeparture("01AUG07", "14:40");
if (cal.get(Calendar.YEAR) != 2007) { ... }

Categories