Discrepancy in current hour

R

Rhino

Lew said:
Rhino said :


No, I mean of the Java code, duh.
I don't appreciate the "duh". I'm not an idiot but I'm not a psychic
either. I didn't understand what you meant.

I don't think there's anything wrong with the date routines themselves
since they've been working fine for ages. But I did post them in the
original question.
By honoring the actual request.
Obviously, any SSCCE isn't going to show you the screens that come up
when I click on the Windows clock so this example only shows you the Java
code that I am running to display the current time.

---------------------------------------------------
import java.util.Calendar;
import java.util.GregorianCalendar;

public class TestHour {

public static void main(String[] args) {

new TestHour();
}

public TestHour() {

System.out.println("The current hour on the 12 hour clock is: " +
getCurrentHour12HourClock() + ".");
System.out.println("The current hour on the 24 hour clock is: " +
getCurrentHour24HourClock() + ".");
System.out.println("The current time is: " + getCurrentTime() +
".");
}

public int getCurrentHour12HourClock() {

GregorianCalendar now = new GregorianCalendar();
return now.get(Calendar.HOUR);
}

public int getCurrentHour24HourClock() {

GregorianCalendar now = new GregorianCalendar();
return now.get(Calendar.HOUR_OF_DAY);
}

public String getCurrentTime() {

GregorianCalendar now = new GregorianCalendar();
int intCurrentHour = now.get(Calendar.HOUR_OF_DAY);
int intCurrentMinute = now.get(Calendar.MINUTE);
int intCurrentSecond = now.get(Calendar.SECOND);

String strCurrentHour = pad(intCurrentHour, '0', 'L', 2);
String strCurrentMinute = pad(intCurrentMinute, '0', 'L', 2);
String strCurrentSecond = pad(intCurrentSecond, '0', 'L', 2);

return strCurrentHour + ":" + strCurrentMinute + ":" +
strCurrentSecond;
}

public String pad(long input, char padChar, char padPosition, int
finalLength) {

String strInput = String.valueOf(input);

if (padPosition != 'L' & padPosition != 'l' & padPosition != 'T'
& padPosition != 't') {
throw new IllegalArgumentException("Type of padding must be 'L',
'l', 'T', or 't'.");
}

if (finalLength < strInput.length()) {
throw new IllegalArgumentException("The value you are
padding is already longer than the final length you want.");
}

int numPadChars = finalLength - strInput.length();
StringBuffer strbuffPaddedString = new StringBuffer();
if (padPosition == 'L' | padPosition == 'l') {
for (int ix = 0; ix < numPadChars; ix++)
strbuffPaddedString.append(padChar);
strbuffPaddedString.append(strInput);
} else {
strbuffPaddedString.append(strInput);
for (int ix = 0; ix < numPadChars; ix++)
strbuffPaddedString.append(padChar);
}

return (strbuffPaddedString.toString());
}

}

---------------------------------------------------

This is the output I got when I ran the SSCCE a few moments ago (at 5:11
PM EDT.)

=============================================
The current hour on the 12 hour clock is: 6.
The current hour on the 24 hour clock is: 18.
The current time is: 18:11:39.
=============================================

Do you agree that the Java code should give me the correct hour?
 
R

Rhino

That's what I'm trying to figure out ;-)
The OS has the correct time.
Crap! I don't know how to check that short of rebooting the computer and
entering the BIOS that way. Even Everest doesn't tell me the BIOS time.
I'll reboot and post the result in a separate reply after I finish this
one.....
I've provided both in a reply to one of Lew's posts.
Wow. I had assumed it was just something foolish that I had done, like not
updating something that I didn't realized needed updating.

It will be interesting to see what you get when you try my SSCCE....
For example, what is this 'StringUtils'? If 'String' formatted
representations are needed of a 'Calendar', what's wrong with using
'DateFormat'?
[ SNIP ]

Rhino mentioned a StringUtils class of his own - it was the subject of
the "Design question" thread dating from 15 March. Although there are
dozens of StringUtils classes put out by various projects, the most
notable probably being Apache Commons Lang, I'm guessing the one here
is likely Rhino's.

The first thing I'm usually suspicious of when a test reports a test
failure is the test itself. As part of one maintenance project back in
2008 I spent the best part of a month fixing defects in a JUnit test
suite; nearly a hundred JUnit tests were themselves broken. They
hadn't necessarily always been - most of them were OK when written -
but they failed to track code changes. But some had clearly always
been wrong.

I think it's a bit crazy to unit test your unit tests, under normal
conditions; nevertheless it's worth keeping in mind that if you can't
keep your tested code error-free then neither can you keep your
testing code error-free, and interpret the output of tests
accordingly.

In that project I mentioned, the tests that had the highest problem
percentage involved date/time code. No surprise there. Both the
date/time code under test, and the date/time code *in* the tests, were
riddled with defects.

Under the circumstances, in this hypothetical SSCCE, I'd be checking
the tests first.

AHS

Arved, you are almost right. The problem I'm having with the hour is with
another class I wrote myself called DateTimeUtils. (I've segregated all
date/time stuff into a class by itself rather than put it into my own
StringUtils).

I think you'll see in the SSCCE that the code should be producing the
correct hour but is an hour later than the actual time.

I've added the SSCCE to another part of the thread, after one of Lew's
remarks.

For what it's worth, my JUnit tests continue to produce the same result,
i.e. the hour by itself or the time (HH:MM:DD) are an hour later than they
should be.

If you'd like to see the JUnit tests, I could include them but I'm pretty
sure that there is nothing wrong with them.
 
R

Rhino

That's what I'm trying to figure out ;-)
The OS has the correct time.
Crap! I don't know how to check that short of rebooting the computer
and entering the BIOS that way. Even Everest doesn't tell me the BIOS
time. I'll reboot and post the result in a separate reply after I
finish this one.....
I've provided both in a reply to one of Lew's posts.
Wow. I had assumed it was just something foolish that I had done, like
not updating something that I didn't realized needed updating.

It will be interesting to see what you get when you try my SSCCE....
For example, what is this 'StringUtils'? If 'String' formatted
representations are needed of a 'Calendar', what's wrong with using
'DateFormat'?
[ SNIP ]

Rhino mentioned a StringUtils class of his own - it was the subject
of the "Design question" thread dating from 15 March. Although there
are dozens of StringUtils classes put out by various projects, the
most notable probably being Apache Commons Lang, I'm guessing the one
here is likely Rhino's.

The first thing I'm usually suspicious of when a test reports a test
failure is the test itself. As part of one maintenance project back
in 2008 I spent the best part of a month fixing defects in a JUnit
test suite; nearly a hundred JUnit tests were themselves broken. They
hadn't necessarily always been - most of them were OK when written -
but they failed to track code changes. But some had clearly always
been wrong.

I think it's a bit crazy to unit test your unit tests, under normal
conditions; nevertheless it's worth keeping in mind that if you can't
keep your tested code error-free then neither can you keep your
testing code error-free, and interpret the output of tests
accordingly.

In that project I mentioned, the tests that had the highest problem
percentage involved date/time code. No surprise there. Both the
date/time code under test, and the date/time code *in* the tests,
were riddled with defects.

Under the circumstances, in this hypothetical SSCCE, I'd be checking
the tests first.

AHS

Arved, you are almost right. The problem I'm having with the hour is
with another class I wrote myself called DateTimeUtils. (I've
segregated all date/time stuff into a class by itself rather than put
it into my own StringUtils).

I think you'll see in the SSCCE that the code should be producing the
correct hour but is an hour later than the actual time.

I've added the SSCCE to another part of the thread, after one of Lew's
remarks.

For what it's worth, my JUnit tests continue to produce the same
result, i.e. the hour by itself or the time (HH:MM:DD) are an hour
later than they should be.

If you'd like to see the JUnit tests, I could include them but I'm
pretty sure that there is nothing wrong with them.

Unfortunately, most of the replies to this thread have now dropped off my
news reader so I can't see most of it any more. Obviously, I'm going to
have to go into Google Groups now to keep up with it.

Anyway, I just rebooted the computer, went into the BIOS and found that
the time there is also correct. It showed the current hour as 5 PM, which
it is. This agrees with the Windows clock and the time.gov website.

Heading over to Google Groups now to keep on top of your replies....
 
E

Eric Sosman

[...]

This is the output I got when I ran the SSCCE a few moments ago (at 5:11
PM EDT.)

=============================================
The current hour on the 12 hour clock is: 6.
The current hour on the 24 hour clock is: 18.
The current time is: 18:11:39.
=============================================

You're getting the data from a bunch of GregorianCalendar
instances (not all the same instance, for some reason), and
you've created them with `new GregorianCalendar()' rather than
with the recommended `Calendar.getInstance()'. That may or may
not have something to do with your problem.

Suggestions:

1) Use one Calendar object instead of several.

2) Print the toString() of that Calendar instance (my bet
is that you'll find it's still in EST).

3) Try using Calendar.getInstance(), and print the toString()
of that object, too, to see if you get EDT this time.

4) Learn to use the format() methods of PrintStream and/or
of String.

5) Refrain from calling non-final instance methods on objects
that haven't finished construction! This is a Big No-No;
don't do it!
 
R

Rhino

It is only relevant for old Java versions.

That's a relief. I was never able to download those files. I've
forgotten the name of my account so I've been trying to create a new
one but the process keeps failing inexplicably. I'm assuming it has
something to do with Oracle taking over Sun and messing with the
systems.
 
R

Rhino

Or something is confusing Windows or the PC itself.

What does the OS claim the time zone is, independently of Java?

Do the OS time and BIOS time match?

Would the OP provide an SSCCE and copy-paste actual output, and a comparison
with what was expected?

The problem has to be in a detail that hasn't reached Usenet yet.

For example, what is this 'StringUtils'?  If 'String' formatted
representations are needed of a 'Calendar', what's wrong with using 'DateFormat'?

I really, really don't think that "it has something to do with Java date
routines not correctly handling the earlier changeover to daylight savings
time" or anything else to do with the standard API, nor do I think it's a
problem with out-of-date tzdata.

I'm deeply suspicious of code that uses a 'Calendar', then extracts fields
from it, then pads the fields back into 'String's.  That's an awful lot of
custom conversion, with lots of room for things to be done wrong, for one to
go around calumnizing the java.* packages.

Look to thine own house first.

I'm prepared to revisit the code and rework it completely if
necessary, although I'd certainly be reluctant to do so since they've
been working fine up until now.
 
R

Rhino

This is the output I got when I ran the SSCCE a few moments ago (at 5:11
PM EDT.)
=============================================
The current hour on the 12 hour clock is: 6.
The current hour on the 24 hour clock is: 18.
The current time is: 18:11:39.
=============================================

     You're getting the data from a bunch of GregorianCalendar
instances (not all the same instance, for some reason), and
you've created them with `new GregorianCalendar()' rather than
with the recommended `Calendar.getInstance()'.  That may or may
not have something to do with your problem.

     Suggestions:

     1) Use one Calendar object instead of several.

     2) Print the toString() of that Calendar instance (my bet
        is that you'll find it's still in EST).

     3) Try using Calendar.getInstance(), and print the toString()
        of that object, too, to see if you get EDT this time.

     4) Learn to use the format() methods of PrintStream and/or
        of String.

     5) Refrain from calling non-final instance methods on objects
        that haven't finished construction!  This is a Big No-No;
        don't do it!

I think you're saying that there is a fundamental flaw in the design
of my class that is causing my trouble. And that's entirely possible.
I'm basically just trying to write a class containing methods that I
can call with a single line of code to get me basic date/time
information. For example, what is the current time? What is the
current hour? etc. etc. The average program that is going to call this
cl;ass is not going to execute all of the methods in it but only a
small handful of them most of the time. If I'm understanding the
terminology correctly, this class is full of "convenience methods".

Therefore, it seems to me that each method should be standalone and
not count on the caller having executed other methods first, aside
from the getInstance() of course.

Under those circumstances, and given that some of the methods don't
even use Calendar, are you saying in your first point that I should be
getting a single instance of Calendar in the getInstance() method that
is then shared with all other methods in this instance?

With regards to your second and third points, I will do that shortly,
after I finish this post.

with regards to your fourth point, are you saying I should be using
format() instead of my own home-grown pad() method? If so, that's
perfectly valid and I have no problem with it. If that's not what you
mean, could you clarify?

With regards to your fifth point, I'm afraid I still get a little
muddled when someone makes a generalized commment like that without
also pointing to the specific thing I've done wrong. Can you clarify
which object hasn't finished construction?
 
R

Rhino

On 3/20/2010 5:21 PM, Rhino wrote:
[...]
This is the output I got when I ran the SSCCE a few moments ago (at 5:11
PM EDT.)
=============================================
The current hour on the 12 hour clock is: 6.
The current hour on the 24 hour clock is: 18.
The current time is: 18:11:39.
=============================================
     You're getting the data from a bunch of GregorianCalendar
instances (not all the same instance, for some reason), and
you've created them with `new GregorianCalendar()' rather than
with the recommended `Calendar.getInstance()'.  That may or may
not have something to do with your problem.
     Suggestions:
     1) Use one Calendar object instead of several.
     2) Print the toString() of that Calendar instance (my bet
        is that you'll find it's still in EST).
     3) Try using Calendar.getInstance(), and print the toString()
        of that object, too, to see if you get EDT this time.
     4) Learn to use the format() methods of PrintStream and/or
        of String.
     5) Refrain from calling non-final instance methods on objects
        that haven't finished construction!  This is a Big No-No;
        don't do it!

I think you're saying that there is a fundamental flaw in the design
of my class that is causing my trouble. And that's entirely possible.
I'm basically just trying to write a class containing methods that I
can call with a single line of code to get me basic date/time
information. For example, what is the current time? What is the
current hour? etc. etc. The average program that is going to call this
cl;ass is not going to execute all of the methods in it but only a
small handful of them most of the time. If I'm understanding the
terminology correctly, this class is full of "convenience methods".

Therefore, it seems to me that each method should be standalone and
not count on the caller having executed other methods first, aside
from the getInstance() of course.

Under those circumstances, and given that some of the methods don't
even use Calendar, are you saying in your first point that I should be
getting a single instance of Calendar in the getInstance() method that
is then shared with all other methods in this instance?

With regards to your second and third points, I will do that shortly,
after I finish this post.

with regards to your fourth point, are you saying I should be using
format() instead of my own home-grown pad() method? If so, that's
perfectly valid and I have no problem with it. If that's not what you
mean, could you clarify?

With regards to your fifth point, I'm afraid I still get a little
muddled when someone makes a generalized commment like that without
also pointing to the specific thing I've done wrong. Can you clarify
which object hasn't finished construction?
Here is my amended SSCCE and the actual output I got a few minutes ago
while the hour was still 6 PM.

import java.util.Calendar;
import java.util.GregorianCalendar;

public class TestHour {

final static boolean DEBUG = true;

public static void main(String[] args) {

new TestHour();
}

public TestHour() {

System.out.println("The current hour on the 12 hour clock is: " +
getCurrentHour12HourClock() + ".\n");
System.out.println("The current hour on the 24 hour clock is: " +
getCurrentHour24HourClock() + ".\n");
System.out.println("The current time is: " + getCurrentTime() + ".
\n");
}

public int getCurrentHour12HourClock() {

/* Get the current date, then the current hour (12 hour
clock). */
GregorianCalendar now = new GregorianCalendar();
if (DEBUG) {
System.out.println("now.toString(): " + now.toString());
System.out.println("Calendar.getInstance().toString(): " +
Calendar.getInstance().toString());
}
return now.get(Calendar.HOUR);
}

public int getCurrentHour24HourClock() {

/* Get the current date, then the current hour (24 hour
clock). */
GregorianCalendar now = new GregorianCalendar();
if (DEBUG) {
System.out.println("now.toString(): " + now.toString());
System.out.println("Calendar.getInstance().toString(): " +
Calendar.getInstance().toString());
}
return now.get(Calendar.HOUR_OF_DAY);
}

public String getCurrentTime() {

/* Get the current time. */
GregorianCalendar now = new GregorianCalendar();
System.out.println("Calendar: " + now.toString());
if (DEBUG) {
System.out.println("now.toString(): " + now.toString());
System.out.println("Calendar.getInstance().toString(): " +
Calendar.getInstance().toString());
}
int intCurrentHour = now.get(Calendar.HOUR_OF_DAY);
int intCurrentMinute = now.get(Calendar.MINUTE);
int intCurrentSecond = now.get(Calendar.SECOND);

/*
* Convert hour, minute, and second values to strings. Pad the
values
* with leading zeroes as necessary to put them in ISO format.
*/
String strCurrentHour = pad(intCurrentHour, '0', 'L', 2);
String strCurrentMinute = pad(intCurrentMinute, '0', 'L', 2);
String strCurrentSecond = pad(intCurrentSecond, '0', 'L', 2);

/* Construct the string representing the current time. */
return strCurrentHour + ":" + strCurrentMinute + ":" +
strCurrentSecond;
}

public String pad(long input, char padChar, char padPosition, int
finalLength) {

/* Convert the input integer to a String. */
String strInput = String.valueOf(input);

/*
* Pad position must be 'l' or 'L' for "leading" or 't' or 'T'
for
* trailing.
*/
if (padPosition != 'L' & padPosition != 'l' & padPosition !=
'T'
& padPosition != 't') {
throw new IllegalArgumentException("Type of padding must be
'L', 'l', 'T', or 't'.");
}

/*
* Final length must be greater than or equal to the length of
the input
* string.
*/
if (finalLength < strInput.length()) {
throw new IllegalArgumentException("The value you are
padding is already longer than the final length you want.");
}

/*
* Determine the number of occurrences of the pad character
that will
* have to be added to the input string.
*/
int numPadChars = finalLength - strInput.length();

/*
* If the pad position is 'L' or 'l' for "leading", write the
pad
* characters followed by the input string. Otherwise, write
the pad
* characters after the input string.
*/
StringBuffer strbuffPaddedString = new StringBuffer();
if (padPosition == 'L' | padPosition == 'l') {
for (int ix = 0; ix < numPadChars; ix++)
strbuffPaddedString.append(padChar);
strbuffPaddedString.append(strInput);
} else {
strbuffPaddedString.append(strInput);
for (int ix = 0; ix < numPadChars; ix++)
strbuffPaddedString.append(padChar);
}

return (strbuffPaddedString.toString());
}

}

The output wraps horribly so I'll just summarize it verbally: The hour
still shows as 7 PM even though it was not yet 7 PM when I executed
the code.
 
M

Martin Gregorie

Actually, I'm NOT trying to blame Roedy's SetClock, I'm trying to
understand the behaviour I am getting. If the problem is in Windows,
that's fine, I'm quite prepared to accept that. For the moment, I'm just
trying to be sure that I'm following Roedy's instructions correctly. The
first point of failure with this kind of thing is usually communications
issues over understanding the instructions, at least in my case.
Which XP service pack are you using? Details are here:

http://www.windowskb.com/Uwe/Forum.aspx/windowsxp/264794/Windows-XP-SP3-
handles-Daylight-Savings-Time-end-incorrectly

How does Your copy of Windows use its RTC? Older Windowses used to insist
on setting the RTC to the local time and dealing with daylight savings
time by resetting the clock at the start and end of DST. Software running
on those versions must not attempt to correct for DST: timezone and
daylight savings offsets are purely documentary on those Windows
versions. They are only relevant to time calculations when the RTC is set
to UTC.

IIRC Windows 7 sets its RTC to UTC and applies timezone and DST offsets
to it when the time is requested. This means the following questions need
answers:

- how does your copy of Windows handle the RTC?

- do Windows Java implementations detect which version they are
running on and use this to determine whether the clock is on local
time or RTC?
 
L

Lew

With regards to your fifth point, I'm afraid I still get a little
muddled when someone makes a generalized commment like that without
also pointing to the specific thing I've done wrong. Can you clarify
which object hasn't finished construction?

'TestHour'.

You call a bunch of methods from inside the constructor, ergo the object
hasn't finished construction when you call methods like
'getCurrentHour12HourClock()'. It is better (usually) to let an object finish
construction before it does anything useful.

(TAB characters removed for readability.)
public TestHour() {

System.out.println("The current hour on the 12 hour clock is: " +
getCurrentHour12HourClock() + ".\n");
System.out.println("The current hour on the 24 hour clock is: " +
getCurrentHour24HourClock() + ".\n");
System.out.println("The current time is: " + getCurrentTime() + ".
\n");
}

And please, please, please, please, please use narrower indentation for Usenet
code posts - a maximum of four spaces per indent level. It makes the code so
hard to read when you use such wide indentation. Stop using TAB characters
for indentation.
The output wraps horribly so I'll just summarize it verbally:
The hour still shows as 7 PM even though it was not yet 7 PM
when I executed the code.

The actual output still has a marginal chance of being useful to those of us
not there who attempt to help from here. Every time you redact information
you risk losing the piece that solves the puzzle.
 
A

Arved Sandstrom

Rhino wrote:
[ SNIP ]
If you'd like to see the JUnit tests, I could include them but I'm pretty
sure that there is nothing wrong with them.

It can't hurt - you've asked for feedback concerning testing in general,
and JUnit specifically, and that's a good way to get some.

AHS
 
A

Arved Sandstrom

Rhino wrote:
[ SNIP ]
Therefore, it seems to me that each method should be standalone and
not count on the caller having executed other methods first, aside
from the getInstance() of course.
[ SNIP ]

This is not functional programming so whether methods are standalone or
not is entirely your business. OOP is loaded with examples of methods
requiring other methods to execute first. You should be clear in your
own mind as to what methods behave like pure functions and which don't,
however.

AHS
 
R

Rhino

Which XP service pack are you using? Details are here:

http://www.windowskb.com/Uwe/Forum.aspx/windowsxp/264794/Windows-XP-SP3-
handles-Daylight-Savings-Time-end-incorrectly

How does Your copy of Windows use its RTC? Older Windowses used to insist
on setting the RTC to the local time and dealing with daylight savings
time by resetting the clock at the start and end of DST. Software running
on those versions must not attempt to correct for DST: timezone and
daylight savings offsets are purely documentary on those Windows
versions. They are only relevant to time calculations when the RTC is set
to UTC.

IIRC Windows 7 sets its RTC to UTC and applies timezone and DST offsets
to it when the time is requested. This means the following questions need
answers:

- how does your copy of Windows handle the RTC?

- do Windows Java implementations detect which version they are
  running on and use this to determine whether the clock is on local
  time or RTC?

I'm running XP SP2, not SP3. I asked about DST issue on one of the
Microsoft newsgroups and they pointed me to a web page which is
supposed to help me install whatever I need. I went to that page, and
had to identify my skill level; I chose programmer and it started
blathering about C# and .NET but I don't develop in those. So I re-
selected the skill level to home user. It asked me which program I was
updating; I chose Outlook 2007 but it failed to execute with a cryptic
error message.

Frankly, I suspect the OS very strongly here but am baffled about what
I need to do to fix this issue.

If you can enlighten me, I'd appreciate it.
 
R

Rhino

'TestHour'.

You call a bunch of methods from inside the constructor, ergo the object
hasn't finished construction when you call methods like
'getCurrentHour12HourClock()'.  It is better (usually) to let an object finish
construction before it does anything useful.
Okay, I see your point now. (Well, actually it was Eric's point and
you are clarifying it.) But I'm not clear on what I have to do
differently. How do I know the object has finished construction so
that I know it is safe to use it? In other words, how should I code it
differently.

For what it's worth, your point is well taken that I should be using
DateFormat and SimpleDateFormat. I'm actually rewriting my methods to
use that approach as I wait for replies to my problem. I think I
originally wrote my DateTimeUtils class before I knew about DateFormat
and SimpleDateFormat so my code is way overdue to be brought up to
date anyway.
(TAB characters removed for readability.)



And please, please, please, please, please use narrower indentation for Usenet
code posts - a maximum of four spaces per indent level.  It makes the code so
hard to read when you use such wide indentation.  Stop using TAB characters
for indentation.
Sorry about that! The tabs just look like spaces and its hard to find
them all.
The actual output still has a marginal chance of being useful to those of us
not there who attempt to help from here.  Every time you redact information
you risk losing the piece that solves the puzzle.
Okay, I'll include that as well.

Also for what it's worth, when I wrote the code using
SimpleDateFormat, the hour is still one hour later than it should be.

Now for some new output.

I've modified TestHour slightly to display the values you've
requested. I modified the three methods along these lines and added a
single instance variable, DEBUG which is a boolean set to true.

public int getCurrentHour12HourClock() {

/* Get the current date, then the current hour (12 hour clock). */
GregorianCalendar now = new GregorianCalendar();
if (DEBUG) {
System.out.println("now.toString(): " + now.toString());
System.out.println("Calendar.getInstance().toString(): " +
Calendar.getInstance().toString());
}
return now.get(Calendar.HOUR);
}

Each of the three methods were modified in exactly the same way with
the exact same if (DEBUG) and the exact same printlin() statements in
the exact same position within the method.

This is the output from running TestHour, INCLUDING all the output
from the new println() statements.

--------------------------------------------
now.toString():
java.util.GregorianCalendar[time=1269135963921,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/
New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/
New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2010,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=3,DAY_OF_MONTH=20,DAY_OF_YEAR=79,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=46,SECOND=3,MILLISECOND=921,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
Calendar.getInstance().toString():
java.util.GregorianCalendar[time=1269135963937,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/
New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/
New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2010,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=3,DAY_OF_MONTH=20,DAY_OF_YEAR=79,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=46,SECOND=3,MILLISECOND=937,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
The current hour on the 12 hour clock is: 9.

now.toString():
java.util.GregorianCalendar[time=1269135963937,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/
New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/
New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2010,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=3,DAY_OF_MONTH=20,DAY_OF_YEAR=79,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=46,SECOND=3,MILLISECOND=937,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
Calendar.getInstance().toString():
java.util.GregorianCalendar[time=1269135963937,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/
New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/
New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2010,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=3,DAY_OF_MONTH=20,DAY_OF_YEAR=79,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=46,SECOND=3,MILLISECOND=937,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
The current hour on the 24 hour clock is: 21.

Calendar:
java.util.GregorianCalendar[time=1269135963937,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/
New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/
New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2010,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=3,DAY_OF_MONTH=20,DAY_OF_YEAR=79,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=46,SECOND=3,MILLISECOND=937,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
now.toString():
java.util.GregorianCalendar[time=1269135963937,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/
New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/
New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2010,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=3,DAY_OF_MONTH=20,DAY_OF_YEAR=79,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=46,SECOND=3,MILLISECOND=937,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
Calendar.getInstance().toString():
java.util.GregorianCalendar[time=1269135963937,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/
New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/
New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2010,MONTH=2,WEEK_OF_YEAR=12,WEEK_OF_MONTH=3,DAY_OF_MONTH=20,DAY_OF_YEAR=79,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=46,SECOND=3,MILLISECOND=937,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
The current time is: 21:46:03.


--------------------------------------------

As you see, the hour is now indicated as 9/21 but it is still not
quite 9 PM here so the hour is still one hour later than the actual
time.

I've also rewritten the routines along the lines you suggested with
DateFormat and SimpleDateFormat and now present TestHour2:

-------------------------------------------
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestHour2 {

final static boolean DEBUG = true;

public static void main(String[] args) {

new TestHour2();
}

public TestHour2() {

System.out.println("The current hour on the 12 hour clock is: " +
getCurrentHour12HourClock() + ".\n");
System.out.println("The current hour on the 24 hour clock is: " +
getCurrentHour24HourClock() + ".\n");
System.out.println("The current time is: " + getCurrentTime() + ".
\n");
}
public int getCurrentHour12HourClock() {

Date now = new Date();
SimpleDateFormat hourFormat = new SimpleDateFormat("h");
String strCurrentHour = hourFormat.format(now).toString();
int currentHour = 0;
try {
currentHour = Integer.parseInt(strCurrentHour.trim());
}
catch (NumberFormatException nf_excp) {
throw new NumberFormatException("The current hour is not an
integer.");
}
return(currentHour);
}

public int getCurrentHour24HourClock() {

Date now = new Date();
SimpleDateFormat hourFormat = new SimpleDateFormat("H");
String strCurrentHour = hourFormat.format(now).toString();
int currentHour = 0;
try {
currentHour = Integer.parseInt(strCurrentHour.trim());
}
catch (NumberFormatException nf_excp) {
throw new NumberFormatException("The current hour is not an
integer.");
}
return(currentHour);
}

public String getCurrentTime() {
Date now = new Date();
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss");
String strCurrentTime = timeFormat.format(now).toString();
return(strCurrentTime);
}
}

-------------------------------------------

The output from this version of the date routines is, as you might
have guessed:

-------------------------------------------
The current hour on the 12 hour clock is: 9.

The current hour on the 24 hour clock is: 21.

The current time is: 09:58:06.
-------------------------------------------

In other words, rewriting the methods to use better techniques still
causes the hour to be one hour later than it should be.

Have we proven now that the problem is with the OS or is there still a
chance that this is a Java issue?
 
R

Rhino

Rhino wrote:

[ SNIP ]
If you'd like to see the JUnit tests, I could include them but I'm pretty
sure that there is nothing wrong with them.

It can't hurt - you've asked for feedback concerning testing in general,
and JUnit specifically, and that's a good way to get some.

AHS

Here are the test cases for the three methods that are giving me the
wrong hour. As you can imagine, the hour changes regularly -
hourly ;-) - so I have to keep revising the expectedResult to match.
(This is a much bigger problem with the second and millisecond by the
way! I wonder what a professional test class would do to make it
unnecessary to recode the expected hour, minute, second (or whatever)
by hand all the time....)

------------------------------------

public void testGetCurrentHour12() {

//TODO: why does this method return 9 (PM) when it is actually 8 in
this time zone right now?
int currentHour = dateTimeUtils.getCurrentHour12HourClock();
int expectedHour = 8;
assertTrue("The actual hour (12 hour clock), " + currentHour + ",
does not equal the expected hour, " + expectedHour,
currentHour==expectedHour);
}

public void testGetCurrentHour24() {

//TODO: why does this method return 21 hours (24-hour clock) when it
is actually 20 in this time zone right now?
int currentHour = dateTimeUtils.getCurrentHour24HourClock();
int expectedHour = 20;
assertTrue("The actual hour (24 hour clock), " + currentHour + ",
does not equal the expected hour, " + expectedHour,
currentHour==expectedHour);
}

public void testGetCurrentTime() {
String currentTime = dateTimeUtils.getCurrentTime();
String expectedTime = "20:24:00"; //$NON-NLS-1$
assertTrue("The actual time, " + currentTime + ", does not equal the
expected time, " + expectedTime, currentTime.equals(expectedTime));
}
 
M

Martin Gregorie

I'm running XP SP2, not SP3. I asked about DST issue on one of the
Microsoft newsgroups and they pointed me to a web page which is supposed
to help me install whatever I need. I went to that page, and had to
identify my skill level; I chose programmer and it started blathering
about C# and .NET but I don't develop in those. So I re- selected the
skill level to home user. It asked me which program I was updating; I
chose Outlook 2007 but it failed to execute with a cryptic error
message.

Frankly, I suspect the OS very strongly here but am baffled about what I
need to do to fix this issue.

If you can enlighten me, I'd appreciate it.
I've been purely a Linux user for the last 8 years, so the last Windows
version I understand in any depth is Win95. I still have it installed for
the rare occasions when I need to run a couple of programs I haven't yet
tried to run under Wine. That box dual-boots, so I am very familiar with
local-clock Win95 and UTC Linux fighting over the RTC. My only experience
of a more recent Window was a three month contract writing Java with
IntelliJ on an XP box, which I treated as a black box platform since
testing, etc. was done under RHEL.

This is why I posed the questions I'd want to look into rather than
giving you answers.
 
A

Arved Sandstrom

Rhino said:
Okay, I see your point now. (Well, actually it was Eric's point and
you are clarifying it.) But I'm not clear on what I have to do
differently. How do I know the object has finished construction so
that I know it is safe to use it? In other words, how should I code it
differently.
[ SNIP ]

Section 12.5 of the Java Language Specification (JLS) discusses creation
of new class instances, but for your purposes what it boils down to is
that the last things to execute before you get a finished ready-to-go
object are the statements in the body of your constructor (excepting
this() and super() statements, which occur earlier). IOW, when you leave
the body of the constructor is when you've got your finished object.

AHS
 
L

Lew

Rhino said:
public void testGetCurrentHour12() {

//TODO: why does this method return 9 (PM) when it is actually 8 in
this time zone right now?
int currentHour = dateTimeUtils.getCurrentHour12HourClock();
int expectedHour = 8;
assertTrue("The actual hour (12 hour clock), " + currentHour + ",
does not equal the expected hour, " + expectedHour,
currentHour==expectedHour);
}


Just out of curiosity, if you put, just after the declaration of
'expectedHour', the line

Calendar calinst = Calendar.getInstance()
int calendarHour = calinst.get( Calendar.HOUR );

what does it give you?

While we're at it, what do

calinst.getTimeZone.getDisplayName()
and
calinst.getTimeZone.getOffset( calinst.getTimeInMillis() )

return?
Are we agreed that these test cases are okay?

I wonder why you write a utility method to get the current hour when the
standard API already provides a one-line way to do so.
 
L

Lew

Rhino said:
Okay, I see your point now. (Well, actually it was Eric's point and
you are clarifying it.) But I'm not clear on what I have to do
differently. How do I know the object has finished construction so
that I know it is safe to use it? In other words, how should I code it
differently.
[ SNIP ]

Arved said:
Section 12.5 of the Java Language Specification (JLS) discusses creation
of new class instances, but for your purposes what it boils down to is
that the last things to execute before you get a finished ready-to-go
object are the statements in the body of your constructor (excepting
this() and super() statements, which occur earlier). IOW, when you leave
the body of the constructor is when you've got your finished object.

IOW, where your code 'main()' now has 'new TestHour()', it would have instead
something similar to

TestHour th = new TestHour();
th.showResults();

or simply

new TestHour().showResults();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top