Java Reference
In-Depth Information
The time difference is the number of years multiplied by 365, plus the number of leap days
between the two dates (in the years 1904, 1908, . . . , 1968)—i.e., 19 days.
The integer that we read from the server is a C-language
unsigned int
. But Java doesn't
provide an unsigned integer type; normally when you need an unsigned number, you use the
next-larger integer type, which would be
long
. But Java also doesn't give us a method to
read an unsigned integer from a data stream. The
DataInputStream
method
readInt()
reads Java-style signed integers. There are
readUnsignedByte()
methods and
readUnsignedShort()
methods, but no
readUnsignedInt()
method. Accordingly, we syn-
thesize the ability to read an unsigned
int
(which must be stored in a
long
, or else you'd
lose the signed bit and be back where you started from) by reading unsigned bytes and reas-
sembling them using Java's bit-shifting operators:
LocalDateTime
object to show the current date and time on the local (client) machine:
$
java network.RDateClient dalai
Remote time is 3600895637
BASE_DIFF is 2208988800
Time diff == 1391906837
Time on dalai is Sat Feb 08 19:47:17 EST 2014
Local date/time = 2014-02-08T19:47:17.703
$
The name
dalai
is the hostname of one of my OpenBSD Unix computers. Looking at the out-
put, you can see that the server agrees within a second. So the date calculation code in
code is called
RDateClient
.
Example 13-6. RDateClient.java
public
public class
RDateClient
{
/** The TCP port for the binary time service. */
public
class
RDateClient
public static
short
TIME_PORT
=
37
;
/** Seconds between 1970, the time base for Date(long) and Time.
* Factors in leap years (up to 2100), hours, minutes, and seconds.
* Subtract 1 day for 1900, add in 1/2 day for 1969/1970.
*/
protected
static final
final
short
protected static
static final
final
long
long
BASE_DAYS
=
(
long
long
)((
1970
-
1900
)*
365
+ (
1970
-
1900
-
1
)/
4
);
/* Seconds since 1970 */