Java(或者其他java编程软件下载语言)为什么日期是从1970年1月1日0时(midnight, January 1, 1970 UTC)算起?

问题由来:之前在JS中学到Date对象时,时间是从日0时开始的,现在看Java居然也是这样,就很好奇,为什么时间都用这个时间点来计算。然后百度了下,发现有一个很好的帖子描述了这个问题。现在转载过来,以备忘。
原文连接:
看完后自己的理解就是,早期Unix等机器都是32位,那么表示的时间长度有限,只能从1901年到2038年,那么过了2038年时间就会回到1901年。这样就有问题。不过这个最后随着64位机器的诞生就解决了。因为时间可以表示
2^63/86400 ~ 1E14(天) ~ 2.92E11(年)
大约是2920亿年。 足够了^o^/
具体还是把这个分析过程贴在这里,以免那个那个网页消失了。哈哈,相信简书会存活很久吧。
以下是转载
为什么编程语言以及数据库要从日开始计算时间
今天在看Python
API时,看到time模块:
The epoch is the point where the time starts. On January 1st of that year, at 0 hours,the “time since the epoch” is zero. For Unix, the epoch is 1970. To find out what the epoch is, look at gmtime(0).
定义time从日开始,忽然想到在JAVA里,Oracle数据库时间也是从日开始计算。
比如java类代码
Date date = new Date(0);
System.out.println(date);
打印出来的结果:
Thu Jan 01 08:00:00 CST 1970
也是日,实际上时分秒是0点0分0秒(这里打印出来是8点,稍后会作解释)。
为什么这个时间会定义在日这个时候呢?
于是开始了Google,中文网页根本找不到答案。于是试着搜索英文关键字,在Sun java论坛总算找到准确的帖子:
其中有一个回复:
I suspect that Java was born and raised on a UNIX system.
UNIX considers the epoch (when did time begin) to be midnight, January 1, 1970.
是说java起源于UNIX系统,而UNIX认为日0点是时间纪元.
但这依然没很好的解释&为什么&,出于好奇,继续Google,总算找到了答案:
这里的解释是:
最初计算机操作系统是32位,而时间也是用32位表示。
System.out.println(Integer.MAX_VALUE); Integer在JAVA内用32位表示,因此32位能表示的最大值是。另外1年365天的总秒数是,/ = 68.1。也就是说32位能表示的最长时间是68年,而实际上到日03时14分07秒,便会到达最大时间,过了这个时间点,所有32位操作系统时间便会变为00 也就是日20时45分52秒,这样便会出现时间回归的现象,很多软件便会运行异常了。
到这里,我想问题的答案已经出来了:
因为用32位来表示时间的最大间隔是68年,而最早出现的UNIX操作系统考虑到计算机产生的年代和应用的时限综合取了日作为UNIX TIME的纪元时间(开始时间),而java自然也遵循了这一约束。至于时间回归的现象相信随着64为操作系统的产生逐渐得到解决,因为用64位操作系统可以表示到292,277,026,596年12月4日15时30分08秒,相信我们的N代子孙,哪怕地球毁灭那天都不用愁不够用了,因为这个时间已经是千亿年以后了。
最后一个问题:上面System.out.println(new Date(0)),打印出来的时间是8点而非0点,原因是存在系统时间和本地时间的问题,其实系统时间依然是0点,只不过我的电脑时区设置为东8区,故打印的结果是8点。
我想以上问题如果作为面试题,也能难倒一批人了.
转自:,原文标题:为什么编程语言以及数据库要从日开始计算时间,发表时间: 13:48:46。
Linux程式设计-29.时间处理
UNIX及Linux的时间系统是由「新纪元时间」Epoch开始计算起,单位为秒,Epoch则是指定为1970年一月一日凌晨零点零分零秒,格林威治时间。
目前大部份的UNIX系统都是用32位元来记录时间,正值表示为1970以後,负值则表示1970年以前。我们可以很简单地计算出其时间领域:
2^31/86400(s) = (天) ~ 68.0958(年)
时间领域为[38.0958]。
准确的时间为2038年一月十八日星期一晚上十点十四分七秒。那一刻,时间将会转为负数,变成1901年十二月十三日黑色星期五下午三点四十五分五十二秒,然後Jason就会跑出来用斧头砸掉您的电脑。
这就是所谓的UNIX 2038 BUG,或者您也可戏称为Jason hatchet bug。在大部份的UNIX上,并没有所谓Y2K问题,不过都有2038年问题。
在一些64位元的平台上,例如Digital Alpha、SGI、Sparc等等,则用64位元来表示时间。
2^63/86400 ~ 1E14(天) ~ 2.92E11(年) 。大约是2920亿年。
因此,使用64位元的电脑可能会有 Armageddon bug 的问题。届时位於猎户座旋臂的太阳,已经是黑矮星或暗黑物质,猎户座旋臂大概也已经被重力波震断,银河系大概则已经变成小型似星体了。
虽然许多人认为UNIX的2038年问题会随着科技的进步,而将电脑逐步汰换成64位元电脑,因此无须担心。但我个人相信,在2038年,依然会有许多状况出现。因为,就事实而言,目前许多UNIX系统都有足够的能力服役到2038年而毫无问题。因此,如果有意添购电脑主机,而且有预期会使用到那个时候,最好是选购64位元电脑,确认只有世界末日问题(除非您想要把资料流传给下一个宇宙,那就要另当别论了)。
(果然刚才访问这篇文章的原帖,已经404)
深入分析Linux内核源码
以上我们了解了RTC(实时时钟、硬件时钟)和OS时钟(系统时钟、软时钟)。下面我们具体描述OS时钟。OS时钟是由可编程定时/计数器产生的输出脉冲触发中断而产生的。输出脉冲的周期叫做一个“时钟滴答”。计算机中的时间是以时钟滴答为单位的,每一次时钟滴答,系统时间就会加1。操作系统根据当前时钟滴答的数目就可以得到以秒或毫秒等为单位的其他时间格式。
定义“时间基准”的目的是为了简化计算,这样计算机中的时间只要表示为从这个时间基准开始的时钟滴答数就可以了。
阅读(...) 评论()C语言-12-日期和时间处理标准库详细解析及示例
来源:博客园
概述标准库
提供了用于日期和时间处理的结构和函数是C++语言日期和时间处理的基础与时间相关的类型clock_t,本质是:unsigned longtypedef unsigned long __darwin_clock_t;typedef __darwin_clock_t clock_t;time_t,本质是:longtypedef long __darwin_time_t;typedef __darwin_time_t
time_t;size_t,本质是:unsigned long,其中包含条件编译指令// size_ttypedef __darwin_size_t
size_t;// _darwin_size_t#if defined(__SIZE_TYPE__)typedef __SIZE_TYPE__
__darwin_size_t;#elsetypedef unsigned long
__darwin_size_t;#endiftm 结构struct tm {
/* seconds after the minute [0-60] */
/* minutes after the hour [0-59] */
/* hours since midnight [0-23] */
/* day of the month [1-31] */
/* months since January [0-11] */
/* years since 1900 */
/* days since Sunday [0-6] */
/* days since January 1 [0-365] */
/* Daylight Savings Time flag */
/* offset from CUT in seconds */
/* timezone abbreviation */};标准库函数time_t time(time_t *time)返回系统当前日历时间,自日以来经过的秒数;如果系统没有时间,则返回.1,如:time_seconds = time(0);char ctime(const time_t time)返回一个表示当地时间的字符串指针,格式为:Wed Feb 17 15:23:46 2016(与系统有关)char *date = ctime(&seconds);struct tm localtime(const time_t time)返回指向表示本地时间的tm结构的指针tm *localTime = localtime(&seconds);clock_t clock(void)该函数返回程序执行起(一般为程序的开头),处理器时钟所使用的时间,如:clock_t clockTime = clock();char asctime(const struct tm time)该函数返回一个指向字符串的指针,字符串包含了 localTime 所指向结构中存储的信息,格式为:Wed Feb 17 15:48:45 2016date = asctime(localTime);struct tm gmtime(const time_t time)该函数返回一个指向 localTime 的指针,localTime 为 tm 结构,用协调世界时(UTC)也被称为格林尼治标准时间(GMT)表示localTime = gmtime(&seconds);date = asctime(localTime);time_t mktime(struct tm *time)该函数返回日历时间,相当于 time 所指向结构中存储的时间seconds = mktime(localTime);double difftime(time_t time2, time_t time1)该函数返回 time1 和 time2 之间相差的秒数double difference = difftime(seconds, seconds1);size_t strftime(char str, size_t maxsize, const char format, const struct tm *timeptr)`可用于格式化日期和时间为指定的格式格式说明符%a缩写的星期几名称Sun%A完整的星期几名称Sunday%b缩写的月份名称march%B日期和时间表示法Wed Feb 17 08:07:12 2016%d一月中的第几天(01-31)28%H24 小时格式的小时(00-23)23%I12 小时格式的小时(01-12)09%j一年中的第几天(001-366)366%m十进制数表示的月份(01-12)09%M分(00-59)59%pAM 或 PM 名称PM%S秒(00-59)09%U一年中的第几周,以第一个星期日作为第一周的第一天(00-53)53%w十进制数表示的星期几,星期日表示为 0(0-6)6%W一年中的第几周,以第一个星期一作为第一周的第一天(00-53)1%x日期表示法02/17/16%X时间表示法08:14:44%年份,最后两个数字(00-99)99%Y年份2016%Z时区的名称或缩写CST%%一个 % 符号%示例strftime(date, 99, "%Y年%m月%d日 %A %p %I:%M:%S", localTime);// 打印结果:日 Monday AM 08:53:33示例完整代码```#include &stdio.h&#include &time.h&int main(int argc, const char * argv[]) {
seconds = time(0);
printf("%ld\n", seconds);
char *date = ctime(&seconds);
printf("%s\n", date);
struct tm *localTime = localtime(&seconds);
printf("%d\n", localTime-&tm_sec);
clock_t clockTime = clock();
printf("%lu\n", clockTime);
date = asctime(localTime);
printf("%s\n", date);
localTime = gmtime(&seconds);
date = asctime(localTime);
printf("%s\n", date);
time_t seconds1 = mktime(localTime);
printf("%ld\n", seconds1);
double difference = difftime(seconds, seconds1);
printf("%f\n", difference);
strftime(date, 99, "%Y年%m月%d日 %A %p %I:%M:%S", localTime);
printf("%s\n", date);
return 0;}```
免责声明:本站部分内容、图片、文字、视频等来自于互联网,仅供大家学习与交流。相关内容如涉嫌侵犯您的知识产权或其他合法权益,请向本站发送有效通知,我们会及时处理。反馈邮箱&&&&。
学生服务号
在线咨询,奖学金返现,名师点评,等你来互动3303人阅读
MATH FUNCTIONS IN JAVA
Java中的数学函数
(此文原文有较多错误,所有错误已在译文中改正,但原文中的错误,如希腊字母不能正确显示,许多前后单字间还缺少空格等,因工作量太大未全部改正。如果你阅读原文,要注意一些才是。)
334 Getting the Absolute Value ofa Number
334 求数的绝对值
Javas java.lang.Math class provides avariety of static methods for exponentiation, floating-point trigonometry, minand max functions, as well as other operations. Because they are all staticmethods, your programs can reference
them by the class name without having tocreate an instance of the class. Several of the following Tip discuss thesemathematical methods in detail.
Java的java.lang.Math类为我们提供了多种类型的静态方法,可用来实现指数、浮点三角函数、最大和最小、以及其它运算。由于它们都是静态方法,在程序中你可通过类名来引用它们,无需创建类的实例。以下诀窍详细讨论这些数学方法。
To return the absolute value of a number, the Math classprovides four overloaded methods all named abs. The methods support the fournumeric types, int, long, float, and double:
为了返回一个数的绝对值,由Math类提供了四个都叫abs()的相同方法,分别用来支持int、long、float以及double四种数据类型:
public static intabs(int a);
public static longabs(long a);
public static floatabs(float a);
public static doubleabs(double a);
For example, to return the absolute value of a float, you canuse the abs method, as shown:
例如,为了返回一个浮点数的绝对值,你可按下面的方式使用abs()方法:
float num = -5.8F;
num =Math.abs(num);& // Assigns the value 5.8F
335 Using the sqrt Method
335 sqrt方法的使用
When your programs perform arithmetic operations,there will betimes when you will need to take the square root of a value. In such cases,your programs can use the Math class sqrt method. The
format of the sqrt methodis as follows:
当你的程序在执行算术运算时,有时需要计算一个数的平方根。这时,你的程序可使用Math类中的sqrt方法。sqrt 方法的格式如下:
public static doublesqrt(double a) throws ArithmeticE
The following statements, for example, use the Math class sqrtmethod to return the square root of the value 7.9:
例如,以下语句是利用Math类中的sqrt方法来返回数7.9的平方根:
float num = 7.9F;
num = (float) Math.sqrt(num);& // return the square root value
& & & & & & & & & & & & & & & & & & & & & & & & & & // 返回平方根值
Notice that this statement uses an explicit cast to assign thereturn value to a float because the sqrt method returns a double. In this case,the variable num will have a value of 2.81069 after the assignment.
注意,这一语句用强制类型转换方式指定返回数值为float型,因为在缺省时sqrt方法返回的值为double型。在本例中,变量num在赋值后所得到的值将是2.81069。
336 Using the cos Method
335 cos方法的使用
For a triangle, the cosine of an angle is the ratio of the angles adjacent edge to the hypotenuse. The Math class cos method returns thecosine of an angle expressed in radians. The declaration of the cos function isas follows:
在一直角三角形中,一个角的余弦(cosine)就是此角的邻边与斜边的比。Math类中的cos方法返回用弧度表示的角的余弦值。cos函数的说明如下:
public static doublecos(double a);
To return the cosine of an angle, you can use the cos method, asshown:
要得到一个角的余弦,你可按以下形式来使用cos方法:
double num, angle =0.785398D;&& // angle in radians , 角的弧度值
num =Math.cos(angle);&&&&&&&&&& // return thecosine of the angle,返回角的余弦
In this case, the statements will assign the variable num thevalue of 0.707107。
在本例子中,语句将把0.707107赋给变量num作为其值。
337 Using the sin Method
337 sin方法的使用
In a triangle, the sine of an angle is the ratio of the angles opposite edge to the hypotenuse. The Math class sin method returns the sine ofan angle expressed in radians. The declaration of the sin method is as follows:
在一个直角三角形中,一个角的正弦(sine)就是此角的对边与斜边的比。Math类中的sin方法返回用弧度表示的角的正弦值。方法sin的说明如下:
public static doublesin(double a);
To return the sine of an angle, you can use the sin method, asshown:
要得到一个角的正弦,你可按如下所示来使用方法sin:
double num, angle =0.785398D;&& // angle in radians, 1/4
num =Math.sin(angle);&&&&&&&&&& // return thesine of the angle
In this case, the statements will assign the variable num avalue of 0.707107.
在本例子中,语句将把0.707107赋给变量num作为值。
338 Using the tan Method
338 tan方法的使用
In a triangle, the tangent of an angle is the ratio of theangles opposite edge to the adjacent edge. The Math class tan method returnsthe tangent of an angle expressed in radians. The declaration of the tan methodis as follows:
在一个直角三角形中,一个角的正切(tangent)就是此角的对边与邻边的比。在Math类中的tan方法返回用弧度表示的角的正切值。tan方法的说明如下:
public static doubletan(double a);
To return the tangent of an angle, you can use the tan method,as shown:
要得到一个角的正切,你可使用tan方法,如下所示:
double num angle =0.785398D;&&& // angle in radians,1/4 (角的弧度值,等于1/4)
num =Math.tan(angle);&&&&&&&&&& // return thetangent of the angle (返回角的正切)
In this case, the statements will assign the variable num thevalue of 1.0.
在本例中,语句将把1.0赋给变量num作为值。
339 Using the acos Method
339 acos方法的使用 【译注:以下一段原文有概念错误,把邻边/斜边之比(即cos(x)的倒数)当成反三角函数acos,但这应改仍是一个三角函数sec(x)。
译文未译此句,另作解释】
The arccosine is theratio between the hypotenuse of a right triangle and the leg adjac the inverse of the cosine of an angle. If y is the
cosine of x, then x is the arccosine of y. The Math classacos method returns the arccosine of an angle specified in radians. Thedeclaration for the acos function is as follows:
一个角的余弦函数cos(x)是与此角邻边与斜边的比,而反余弦函数acos(x)是余弦函数的逆,即: 如果y是角a的余弦,则角a就是y的反余弦。在Math类中,acos方法返回用弧度表示的反余弦值。acos函数的说明如下:
public static doubleacos(double a);
To return the arccosine of a number, you can use the acosmethod, as shown:
要得到一个数的反余弦,你可使用acos方法,如下所示:
float num = 0.707107F;
num = (float)Math.acos(num);& // 返回反余弦
Notice that these statements use an explicit cast to assign theresult to a float because the acos method returns a double. In this case, numwill have a value of 0.785398 radians after the assignment.
注意,语句用强制类型转换方式指定返回的结果为float型,因为acos方法缺省情况下返回
double型。在本例中,变量num在赋值后所得到的值将是0.785398。
340 Using the asin Method
340 asin方法的使用【译著:以下一段原文同样有概念错】
The arcsine is the ratio between the hypotenuse of a right triangleand the leg opposite the inverse of the sine of an angle.If y is the sine of (, then ( is the arcsine of y. The Math class asin methodreturns
the arcsine of the number as a double. The declaration of the asinmethod is as follows:
一个角的正弦 sin(x)是与此角的对边与三角形的斜边的比,而反正弦asin(x)是一个角的正弦的逆(不是倒数),即: 如果y是角a的正弦,则a就是y的反正弦。在 Math类中,asin方法返回用弧度表示的反正弦值。asin函数的说明如下:
public static doubleasin(double a);
To return the arcsine of a number, you can use the asin method,as shown:
要得到一个数的反正弦,你可使用asin方法,如下所示:
float num = 0.707107F;
num = (float)Math.asin(num);& // return the arcsine
Notice that these statements use an explicit cast to assign thereturn to a float because the asin method returns a double. In this case, numwill have a value of 0.785398 radians after the assignment.
注意,语句用强制类型转换方式指定返回结果为float型,因为asin方法在缺省情况下返回的值为double型。在本例中,变量num在赋值后所得到的值将是0.785398。
341 Using the atan Method
341 atan方法的使用【译著:以下一段原文也有错,见红字部分。译文重写纠正了】
The arctangent is the ratio between the leg adjacent to a givenacute angle and the leg opposite it the inverse of thetangent of an angle. If y is the tangent of (, then (
is the arctangent of y.The atan method in the Math class returns the arctangent of the number as adouble.The declaration of the atan method is as follows:
一个角的正切是与此(锐)角的对边与邻边之比,而反正切是一个角的正切的逆,即:如果y是角a的正切,则a就是y的反正切。在Math类中,方法atan返回用弧度表示的双精度反正切值。atan函数的说明如下:
public static doubleatan(double a);
To return the arctangent of a number, you can use the atanmethod, as shown:
要得到一个数的反正切,你可使用atan方法,如下所示:
double num = 1.0D;
num = Math.atan(num);&// 返回反正切
342 Converting RectangularCoordinates to Polar Coordinates
342 将直角坐标转换成极坐标
In the rectangular coordinate system, the coordinates (x, y)locate a point x units along the x-axis and y units along the y-axis. In thepolar coordinate system, the coordinates (r, () locate a point r units from theorigin and
at an angle ( measured from a reference line. If you have the (x, y)rectangular coordinates and would like to convert them to polar coordinates (r,(), you can use the following equations:
在直角坐标系统中,坐标(x,y)在平面上确定了这样一个点,它沿x轴的分量是x单位,而y轴的分量是y单位。而在极坐标系统中,坐标(ro,thita)在平面上确定了这样一个点,它离原点的距离是ro单元,而与参考线的夹角为thita弧度。如果你已知直角坐标系统中坐标(x,y),想把它们转换成极坐标(ro,thita),则你可用以下两个方程式:
ro = sqrt(x2 + y2)
thita = arctan(y/x)
To implement these equations in Java, use statements similar tothe following:
在Java中要实现这两个方程,可使用以下语句:
float x = 10F, y =20F;
float r = (float)Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
float theta = (float)Math.atan(y/x);
System.out.println(r +&, & + theta);
343 Rounding a FloatingPoint Value Up or Down
343 浮点数的舍入和舍出
The Java Math class provides two methods for rounding a number.The first rounds values of type float to int, and the second rounds values oftype double to long:
Java的Math类提供了两个方法进行数的舍入。第一种方法是把float型浮点数舍入后转换成int型整数,第二种方法则是把double型的双精度数转换成long型长整数:
public static intround(float a);
public static longround(double a);
The following statements illustrate the use of the round method:
以下四个语句示范了舍入方法的使用:
float f1 = 3.8F, f2 =3.2F;
i = Math.round(f1);
j = Math.round(f2);
These statements assign the variable i the value 4, and thevariable j thevalue 3.
这些语句将变量i的值赋为4,而变量j的值赋为3。
344 Finding the LargestWhole Number Less Than or Equal to a Floating-Point number
344 寻找小于等于某一浮点数的最大整数
When you work with floating-point numbers, you may need to rounddown the value to the next lower integer. For such cases, the Java Math classprovides the floor method whose format is as follows:
当你利用浮点数工作时,有时要把数值舍成比此数小的那个整数值。对于这种情况,Java的Math类提供了一个floor方法,它的格式如下:
public static doublefloor(double a);
Unlike the round methods which round up or down to an integer,the floor method rounds down the floating-point number and returns a type thatis also a floating point. For example, the following statements illustrate theuse of the
floor method:
floor与round的舍入方法不同,round方法舍进或舍出后变成了integer型整数,而floor
方法是对float型浮点数进行舍出,并且舍去小数后仍然是一个float型实数。例如,以下
的语句示范了floor方法的使用:
float ff = 3.8F;
float jj = (float)Math.floor(ff);
System.out.println(ff+ & after floor is --& & + jj);
These statements will display the following output:
这些语句将显示以下输出:
3.20000 after floor is--& 3
345 Finding the SmallestWhole Number Greater Than or Equal to a Floating-Point number
345 寻找大于等于某一浮点数的最小整数
When you work with floating-point numbers, you may need to roundup the value to the next higher integer. For such cases, the Java Math classprovides the ceil method, the format of which is as follows:
当你利用浮点数工作时,你可能要把数值舍进成比此数大的那个整数值。对此情况,Java的Math类提供了一个ceil方法,它的格式如下:
public static doubleceil(double a);
Unlike the round methods which round up or down to an integer,the ceil method rounds up the floating-point number and returns a type that isalso a floating point. The following statements illustrate the use of the ceilfunction:
ceil与round的舍入方法不同,round方法舍进或舍出后变成了integer型整数,而ceil方法是对float型浮点数进行舍入,并且返回所得仍然是一个float型实数。以下语句说明了ceil函数的使用:
float ff = 3.2F;
float jj = (float)Math.ceil(ff);
System.out.println(ff+ & after ceil is --& & + jj);
In this case, because the ceil method returns the type doubleand the statements use a variable of type float, the statements use an explicitcast. The statements will display the following output:
在这一例子中,由于ceil方法返回的是double型实数,而语句使用了一个float型的实型
变量,所以在调用的函数表达式之前要加(float)来实行强制类型转换。本语句将显示如下的结果:
3.20000 after ceil is--& 4
346 Rounding a FloatingPoint Value Up or Down to Another Floating Point Value
346 将一浮点数舍入或舍出成为另一浮点数
As you learned in Tip 342, Javas round method will round afloating-point number to an integer. Depending on your programs purpose, youmay want to round the number to another floating-point value. To obtain afloating-point value
from the round method, you simply use an explicit cast toa value of type float or double, as shown:
你在诀窍 342 中已了解,Java的round方法在作舍入转换时将把浮点数转成一个整型数。根据你的程序用途的差别,你有时可能需要在舍入运算后把浮点数转换成另一浮点数。为了由舍入方法得到一浮点数,你只要使用float型或double型的强制类型转换,如:
float f = (float)Math.round(3.8F);
double d = (double)Math.round(3.2F);
These statements will assign the variable f the value 4.0 andthe variable d the value 3.0.
这些语句把变量f赋值为4.0,而把变量d赋值为3.0.
347 Working withExponentials
347 指数函数的利用
When your programs perform complex mathematical operations,there may be times when you need to calculate the exponential of ex。In such cases,your programs can use the Math class exp method. The
following statementillustrates the use of the exp function to determine the result of e0.4:
当你的程序在执行复杂数学运算时,你有可能需要计算以e为底的指数。这时你的程序就可使用Math类中的exp方法,以下这一条语句说明了exp函数的用法,并得到e的0.4次的指数值:
double value =Math.exp(0.4);&& // computes to 1.49183
double value =Math.exp(0.4);&& // 计算结果为1.49183
348 Getting the Value of eor pi
384 获得常数e和pi的值
Javas java.lang.Math class provides two predefined constants.One for e and the other for PI. To obtain these values, specify the Math classname followed by the name of the constant, as shown:
Java的类java.lang.Math提供两个预定义的常数。一个是e,而另一个是pi。为了得到这些值,只要在数学类名Math之后跟随所需常量名即可,如:
System.out.println(eis:& + Math.E);
System.out.println(PIis:& + Math.PI);
These statements, for example, will display the following output:
这两个语句将分别显示以下的结果:
e is: 2.71828
PI is: 3.14159
349 Finding the Remainderof a Floating-Point Division with IEEEremainder
349 寻找带有IEEE余数(IEEEremainder)的浮点除法的余数
As you have learned, the modulo operator (%) returns theremainder of an integer division. Depending on your programs purpose, you maywant to know the remainder of floating-point division. In such cases, the Mathclass provides
the IEEEremainder method to divide two floating-point values,returning the remainder as a floating-point value. The form of theIEEEremainder method is as follows:
你已知道,求模操作(%)能返回整数除法的余数。根据你的程序的用途,你有可能需要计算浮点除法的余数。这时你的程序就可使用Math类中的IEEE余数方法,它对两个浮点数进行相除,并返回浮点的余数。IEEE余数方法的形式如下:&
public static doubleIEEEremainder(double f1, double f2);
For example, if you invoke IEEEremainder with the values 10.0and 3.0, the function will return the value 1.0 (10 divided by 3 is 3 with aremainder of 1). The following statements, for example, will display thefloating-point remainder
to the screen:
例如,如果你调用IEEE余数,并以10.0和3.0作为两个参数,则此函数将返回&#(10除以3得3,余数为1)。例如以下这些语句在屏幕上将显示上述浮点余数:
double n = 10.0;
double d = 3.0;
System.out.println(Math.IEEEremainder(n,d));
350 Calculating Natural Log
350 计算自然对数
The natural logarithm of a number is the power to which thevalue e must be raised to equal the given number. To help your programsdetermine the natural log, the Math class provides the log method, whichreturns the natural logarithm
of a floating point value. The followingstatement illustrates the use of the log function:
一个数的自然对数是一个幂(power),e的这一次方幂就等于已给的那个数。为了帮助你的程序计算自然对数,Math类提供了log方法,它返回一个数的自然对数。以下语句说明了log函数的用法:
double d =Math.log(7.0);& // returns 1.94591
351 Determining Maximum andMinimum Values
351 确定最大最小值
When your programs compare two numbers, there will be times whenyou will want to know the minimum or maximum of two values. For such cases, theMath class provides the min and max methods. You can use these methods tocompare values
of type int, long, float, and double. For example, the followingstatements use the min and max functions to determine the minimum of two valuesof type float and the maximum of two values of type double:
当你的程序在比较两个数的时候,你有时会想要知道两个数中最大或最小的那个数。在这种情况下,你可使用Math类提供的方法min和max。利用这两个方法你就可以比较数的大小,包括int、long、float、double四种类型。例如,以下利用函数min和max的两行语句分别确定两个float型数的最小值和double型数的最大值:
float min =Math.min(3.5F, 4.8F);&&&& // Assigns thevalue 3.5F
double max =Math.max(Math.PI, 3.0);& // Assigns thevalue Math.PI
float min = Math.min(3.5F, 4.8F);&&&& // 赋以数&#2F
double max = Math.max(Math.PI, 3.0);& // 赋以数值 Math.PI
352 Calculating the Resultof Xn
352 计算x的n次幂
One of the most common mathematical operations your programswill perform is to raise a value to a given power. For such cases, the Mathclass provides the pow method, which returns the result of a value raised to agiven power.
The format of the pow method is as follows:
你的程序要执行的最普通的数学运算之一是求一个数的n次升幂。为此, 你可使用Math类提供的方法pow,它返回一个数的n次升幂的结果。pow方法的格式如下:
public static doublelog(double a, double b) throws ArithmeticE
If the result of the value raised to the given power results inoverflow, Java will throw an exception of type ArithmeticException. The powmethod takes two doubles as parameters the first parameter is the base value and the second
is thepower to which the method raises the base. The following statement illustratesthe use of the pow function:
如果已知数的n次升幂的结果产生溢出,Java将抛出一个类型例外(exception of type),叫算术例外(ArithmeticException)。pow方法以两个double型实数作为参数,其中第一个是底(base),第二个是底数需要上升的幂。以下语句示范了pow函数的用法:
double ans =Math.pow(3, 2);& // returns 3 to the 2,or 9
double ans =Math.pow(3, 2);& // 返回 3 的 2 次幂, 即 9
353 Creating RandomFloating-Point numbers Using the Math Class
353 利用Math类创建随机浮点数
Depending on your programs purpose, you may need to generate oneor more random numbers. In such cases, your programs can use the Math classrandom function. The format of the random function is as follows:
根据你程序的用途不同,你可能需要生成一个或多个随机数。在这种情况下,你可使用Math类提供的random方法。random的格式如下:&
public staticsynchronized double random();
The following statements illustrate the use of the random method:
以下语句示例说明方法random的用法:
rand = Math.random();
{kaj verify this statementdoes not seemright}
The random function returns a value in the range 0 to 1.0. Bymultiplying the functions result by a value such as 100 or 1000, your programscan change the range of values.
随机函数返回的值是在0到1.0范围之内的。将所得函数值乘以100或1000,你就可以改变
所得的结果的范围。
354 Understanding PseudoRandom Versus True Random
354 弄清伪随机数与真随机数
When Java, or most other computer languages, needs to produce arandom number, a special calculation is made based on a given input valuecalled a seed number. The calculation will always produce the same number whenthe same seed
number is given. Because the functions result is alwayspredictable, it is called a pseudo-random number. A true-random number is notpredictable.
The fact that the pseudo-random number is predictable does notmean that it cannot make a good random number. The seed number in Java is 64bits long and the algorithm which uses it to create a random number produces agood distribution
of values.
A big advantage of pseudo-random numbers is that your program iseasier to debug when it uses the same sequence of random numbers. After yourelease your software to users, you can ensure good randomness by using adifferent seed
for each program run. For example, the seed could be based onthe time, user keystrokes, network activity, or any other random phenomena.
当Java,或其它计算机语言,需要产生一随机数时,就要利用一个称作种子(数)的已知输入数来进行一种特殊的计算。当给出的是同一种子时,则计算的结果也永远是相同的一个数。这是因为,函数的计算总是确定的,其结果也就总是可以预测的。所以,这样的随机数叫伪随机数。真随机数则应该是不确定的,不可预测的。
伪随机数的可预测性并不意味它不能造就出一个好的随机数。Java的种子数是64位的长整数,算法利用它来产生随机数就能获得优良的值的分布。
伪随机数的一个很大优点在于它可以使程序容易调试,因为它可以使用相同序列的一串数。当你把你的软件交给用户使用后,你可以让每一次运行使用不同的种子以保证产生很好的随机性。例如,你可以根据当时时间、用户的击键次数、上网作业的次数,或其它随机现象来计算种子的数值。
355 Seeding a Random NumberGenerator
355 随机数生成器
Java provides the java.util.Random class which facilitates yourprograms implementation of a pseudo-random number generator. By default, theclass methods uses the current time as the seed value. However, you can use thesetSeed
method or the class constructor to specify a seed value of your own.You may want to do this when, for example, you need to debug code which usesrandom numbers, and you need a repeatable sequence of numbers. For example, youcan use the Random class and set
a starting seed value as follows:
Java提供了一个类java.util.Random,它能简化你的程序实现伪随机数的生成。当缺省时, 该类方法使用当时时间作为种子值。但是,你可以利用方法setSeed或类构造函数(class constructor)来指定你自己的种子值。例如,当你需要调试一个包含随机数的程序时,你就可能需要这样做,你可能需要一个可重复的数的序列。这时,你就可以使用类Random,并按以下方法来设置一初始的种子值:
import java.util.*;
class Randomize {
&& public static void main(String args[])
&&& &&Random r = new Random(123456); // set aninitial seed 设种子初值
&&&&& System.out.println(Random 1 is& + r.nextInt());
&&&&& r.setSeed(654321);& // reset the seed to something else
&&&&&&&&&&&&&&&&&&&&&&&&&&&& 将种子改成其它某个值
&&&&& System.out.println(Random 2 is& + r.nextInt());
The program first sets a seed when it creates the Random classobject. Next, within the call to the System.out.println function, the programcalls the nextInt method, which returns the next integer in the random number sequence.Normally,you
do not need to set a new seed more than once within your programs. However,should you need to do so, you can call the setSeed method, as shown. Thisprogram produces the following output:
本程序在创建对象Random类时首先设置了种子数。然后在函数System.out.println的调用中,程序又调用了方法nextInt,后者返回随机数序列中的下一个整数。通常在你的程序种,除了第一次外,你无需再设置新的种子。但是假如你要这样做,你可以用所示形式来调用setSeed方法。本程序产生以下输出结果:
Random 1 is
Random 2 is
356 Creating RandomFloating-Point Numbers
356 创建随机浮点数
As shown in TIP 358, you can generate random numbers by using aninstance of the Random class. You also learned that the nextInt functionreturns the next integer in a range of random numbers. In a similar way, theRandom class contains
a method called nextFloat, which produces a new randomfloating-point number for each call. The following statements illustrate theuse of the nextFloat method:
如诀窍 358所示{354?}, 你可以利用类random的一个实例来生成随机数。你也知道, 函数nextInt返回的是随机数范围中的下一个整数。用类似的方法,Random类包含一个称作NextFloat的方法,它为每一次调用产生一个新的随机浮点数。以下语句说明nextFloat的用法:
Random r = new Random();&&& // use a default initial seed
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& // 利用缺省初始种子
System.out.println(Randomfloat is& + r.nextFloat());
357 Creating Random Numberswith Gaussian Distribution
357 创建Gause分布随机数
When you create random numbers, you may need better control overthe range of numbers that the random number generator creates. As it turns out,you can produce a set of random numbers based on a Gaussian distribution, thatis, a
distribution having a mean of 0.0 and a standard deviation of 1.0. To getnumbers based on the Gaussian distribution, you use the Random classnextGaussian method, as shown:
当你创建随机数时,你可能需要更好地控制随机数生成器所生成的随机数的范围。当出现这种情况时,你可以利用Gause分布来生成随机数集,Gause分布是这样的一个分布,它的平均值是0.0,而标准偏差是1.0。要获得基于Gause分布的数, 你可以使用随机数类Random的nextGaussian方法, 如下所示:
Random r = newRandom(); // use a default initial seed
&&&&&&&&&&&&&&&&&&&&&&&&&&& // 利用缺省初始种子
System.out.println(Random1 is& + r.nextGaussian());
358 Controlling the Rangeof Random Integers
358 控制随机数的范围
As you have learned, Java programs can generate random integersby using an instance of the Random class. The Random class contains a methodcalled nextInt, which produces a new random int for each call. Depending onyour programs
purpose, you may need to produce random numbers in a specificrange. To control the range of integer values a random-number generatorcreates, you can use the modulus operator (%). For example, if you need numbersin the range -100 to 100, you can get the remainder
of the random
number divided by 100, as shown:&
你已了解, Java程序利用random类的一个实例来生成随机数。random类中包含一个称作NexrInt的方法,它为每一次调用产生一个新的随机整型数。按照你的程序的用途,你可能需要产生某一范围内的随机数。为了控制一随机数建立的整数范围,你可以使用取模运算符(%)。例如,如果你要-100到100范围中的数,你可用100来除随机数而取其余数,如下所示:
Random r = newRandom();&&& // use a default initialseed
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& 利用缺省初始种子
System.out.println(Random int is& + r.nextInt() % 100);
Likewise, if you need to restrict the range of numbers topositive values, say 0 to 100, your programs can use the Math class absfunction, as shown:
同样,如果你要把数值限制在正数范围之内,例如0到100,则你可以在程序中使用Math类的abs函数,如下所示:
Random r = newRandom();&&& // use a default initialseed
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& 利用缺省初始种子
System.out.println(Randomint is& + Math.abs(r.nextInt() % 100));
359 Creating RandomIntegers for a Specific Range
359 在一指定范围中创建随机数
The Random class methods for generating random numbers producevalues in the ranges indicated in Table 359:
生成随机数的Random方法所产生的数值其范围如表359所示:
Method name&&&Range of output
方法名&&&&&&&& 输出范围
------------------------------------------------------------------------
nextFloat&&&&& 从 0.0到 1.0
nextDouble&&&& 从 0.0到 1.0
nextInt&&&&&&& 从- 到
nextLong&&&&&& 从-4775808 到 4775807
------------------------------------------------------------------------
Table 359 Range of random numbers.
表359 随机数的范围
As you learned in Tip 360, by performing simple math operations,you can manipulate the random numbers to produce a desired range. The followingexample shows you how you might limit the range of floating-point randomnumbers from
0 to 100:
你在诀窍 360中已了解, 通过简单的数学运算,你就可控制随机数产生在某一个所希望
的范围内。以下例子向你展示怎样把浮点随机数的范围限制在0到100之内:
Random r = newRandom();& // create a Random object
&&&&&&&&&&&&&&&&&&&&&&&&&&&&& 创建对象Random
float f =r.nextFloat();& // get a random value(0.0 to 1.0)
&&&&&&&&&&&&&&&&&&&&&&&&&& &&&获得0.0-1.0的随机值
float v = (f *100);&&&&& // multiply by a factor to get0 to 100
&&&&&&&&&&&&&&&&&&&&&&&&&&&&& 乘上一因子得到0-100的随机值
<span style="color:#FF Java 诀窍
PAGE 29 of numpages 35
filename jt0375_a
TIME \@ &MMMM d, yyyy&
November 24, 1996
Date Functions in Java
java中的日期函数
&&&&&&&&&&&&&&&&&&&&&&&&&&
360 Getting the Current Date with the Date Class
360 利用Date类获得当前时间
Within your programs, there may be times when your programs willneed to work with the current date and time.As it turnsout, Javas Date class,java.util.Date, provides various methods to
representand manipulate dates and times.If your program callsthe Date constructor with no arguments, a Date instanceis initialized with the current date and time.Becausedifferent parts of the world represent dates in different formats, the Date class provides
a convenient method which formats thecurrent date into the local style.The toLocaleStringmethod will take the date information in the instance and create a Stringobject.For example, thefollowing statements use the Date class methods to display the current
date andtime within the United States:
在你的程序中有时会要求程序在当前日期和当前时间进行工作。当发生这种情况时,你可利用Java的Date类java.util.Date。这一类中包含了许多有关日期与时间的表示和控制的方法。如果你的程序不带参数调用Date构造函数,则一个Date实例就会以当前日期和时间进行初始化。
由于世界不同地区采用不同的&#26684;式表示时间,Date类提供了一种将当前时间&#26684;式化成地区性时间的方便方法。toLocaleString方法将会在实例中取到日期信息,并创建一个 String对象.例如,以下语句利用Date方法在美国国内显示当前日期和时间:
class PrintTheDate {
&& public static void main(String arg[] )
&&&&& Date today= new Date();
&&&&& System.out.println(today.toLocaleString());
The above code will print the date and time, for example:
以上程序将打印类&#20284;以下形示的日期和时间:
Tuesday, 26November, :17 PM
361 Beware of Specifying Dates beyond 2000
361 注意说明2000年后的日期
When your programs work with dates, you need to be careful with dates beyond2000.When you use the setYear method or any of theconstructors that take a year, you are indicating ayear by
the number of years since 1900rather than the centurys last two digits.Therefore, to set the date to the year 2000, you would use the value 100, as follows:
当你的程序利用日期工作时,必须小心日期是否超出2000年。当你使用setYear方法或其它任何带有年份的构造函数时,你常常是指从1900年开始计算的数字,而不是世纪的后两位数字。因此,把日期设定为2000年,你应如下那样使用数&#:
Date future_date= newDate(100, 2, 29);
Note: Some versions of the Java compiler may have a problemrepresenting years beyond 2035.You may want to test your compilers ability toprocess years beyond 2035.
注意: Java编译器的某些版本在表示超过2035年的各个年份时可能会遇到问题。你可能需要测试一下你的编译器处理超过2035年年度的能力。
362 Creating Your Own Date/Time with the Date Class
362 利用Date类建立你自己的日期和时间(以下原文有错!)
Within your programs, you can construct a Date class objectusing the Date method either with parameters (to get the current date and time), or without parameters.If you call the Dateconstructor
with parameters, you may set a specificdate and time.You may also set a particular date andtime after the Date instance is created by calling a specific series of Dateclass methods.
在你的程序中,你可以使用不带参数的Date方法来构造一个Date类对象(这时你将得到当前的日期和时间),也可以使用带有参数的Date方法来构造Date类对象(这时你是用来设置日期和时间).当你调用了一系列Date类方法创建了Date实例之后你可能还要设置特殊的日期和时间。
You may want to create a Date object with a date or timedifferent than the current date or time for a variety of situations.For example, you may need to store dates for specific items
in a database, or perhaps you may need to compare two dates.In any case, the Date class offers severalmethods your programs can use to change dates and times, as shown in Table 362:
你可能要创建一个带有和当前日期和时间不同的日期和时间的Date对象。例如,你可能要为一数据库某指定项存入数据,也或许是要比较两个日期。在任何情况下,你的程序可利用Date类提供的用来改变日期和时间的几个方法, 如表362所示:
方法&&&&&&&&&&& &&&&&&&&&用途
---------------------------------------------------------------------------
setDate(int date)&&&&&&& 设置日期 (day of the month)
setHours(int hours)&&&&& 设置小时
setMinutes(int minutes)& 设置分
setMonth(int month)&&&&& 设置月份数减1(从0开始计月份)
setSeconds(int seconds)& 设置秒
setTime(long time)&&&&&& 设置从1/1/1970开识计算的毫秒数
setYear(long year)&&&&&& 设置从1900年开始的年份数
Table 362 Summary of methods for changing date andtime.
表362 改变日期和时间的方法一览表
For example, to create a Date object with the date, May 31, 1997, youwould use the following statement:
例如,为了建利带有日期日的Date类,你可利用以下的语句:
Date start_date= newDate(97, 4, 31);
363 Using the Date Class to Find the Day of the Week
363 利用Data类计算某年某月某日是星期几
After you create a Date object, either with the current date and time, or with some other date and time, you canobtain the day of the week using the getDay method.TheDate class represents
the day of the week as a zero-based number, with Sunday equal to zero and Saturday equal to six.The following statements will display the day of the week thatcorresponds to the date, May 31, 1997which turns out to be 6 (a Saturday):
在你建立了带有当前日期和时间或其它日期和时间的Date对象之后,利用getDay方法,你即可算出星期几.Date类表示星期几是从0开始算的,即0代表星期天,而6代表星期六.以下语句将显示对应于日是星期几,它应是星期6:
Date start_date = newDate(97, 4, 31);
System.out.println(start_date.getDay());
364 Be Aware that the Day of the Week and Month in theDate Class is
Zero-Based.
364 注意Date类中星期几或几月、几号的计算都是从零为开始算起的
The Date class provides several functions you can use to get orset the current date.When you use the getDay, getMonth, setDay, or setMonth methods, be aware that these methods use zero-based
dates.In other words, the first day of the weekand the first month of the year use the number 0.Forexample, the first day of the week, Sunday, is represented by a 0.The first month of the year, January, is also represented by a 0.Likewise, the last day of
the week, Saturday, is represented by a 6 and the last month,December, is 11.
Date类提供了几种可用来获得或设置当前日期的功能.包括getDay、 getMonth、setDay、或setMonth 等.注意,这些方法在计算时都是从零开始算起的.也就是说,一个星期的第一天、一个月的第一天、以及一年的第一个月,都使用了0.这样,星期天是星期0,每个月的一号是0号,正月是0月,12月则是11月,等。
365 Getting the Current Time with the Date Class
365 利用Date类来计算当前时间
Within your programs, there will be many times when you need todetermine the current time.If your program calls theDate constructor with no arguments, the constructorwill initialize the
Date object with the current date and time.To determine the current time using the Date class, you can use several different techniques.Forexample, the following statements display the currenttime using the toGMTString (to Greenwich Mean Time) getHours, and
getMinutes methods:
你的程序中将会有很多时候需要确定当前的时间.如果你调用Date构造函数时不带参数,则此构造函数将用当前日期和时间来初始化.要利用Date类来确定当前时间,你可以使用几种不同的技术.例如,以下这些语句是利用toGMTString(&#26684;林威治平均时间) getHours和getMinutes方法显示当前时间:
class PrintTheTime {
&& public static void main(String arg[])
&&&&& Date now= new Date();
&&&&&System.out.println(now.toGMTString().substring(12));
&&&&& System.out.println(now.getHours() &#43;&:& &#43; now.getMinutes());
The toGMTString method uses the current Date information toreturn a String representing the Greenwich Mean Time.By using thesubstring method, you can chop off the date informationand just
report the time, as shown here:
以上方法toGMTString利用Date信息来返回代表&#26684;林威治平均时间的一个字符串.借助于子字符串方法,你可以由此截取日期信息和报告当前时间,如:
06:37:16 GMT
To display the current time using a 24-hour format, your programcan concatenate the result of the getHours and getMinutes methods.For example, the previous statements willdisplay the following
要使用24小时制显示当前时间,你的程序可把getHours和 getMinutes方法的结果合在一起.例如,以上语句将产生以下的输出:
366 What Is the Epoch Date?
366 什么是时代日期(Epoch Date)?
Within a Java program, you can create a Date object by specifyinga year, month, date and, optionally, the hour, minute, and second as parameters to theconstructor function.You can also
create a Date objectwith no arguments to the constructor, in which case theDate object will contain the current date and time.Finally, you can create a Date object by specifying the number ofmilliseconds since the epoch date, which is midnightGMT, January
1, 1970.The Date class uses the epoch date as a reference point which letsyour programs refer to subsequent dates in terms
of a single long integer.You cannot set a year before 1970.
在Java程序中,你可以利用对年、月、日,或者再加上对时、分、秒的说明,来创建一Date对象.你也可创建一个在构造函数中不带参数的Date对象,这种情况下,Date对象将包含当前的日期与时间。最后,你可以用指明从时代日期以来的毫秒数的办法,来创建一Date对象。时代日期是指日&#26684;林威治午夜12点。利用以时代日期作为参考点的Date类使你的程序可以使用单个的长整数来谈论其后的时间,但不能设置1970年以前的年份。
367 Getting Current Time in Milliseconds with thegetTime Method
367 利用getTime方法来获得用毫秒表示的当前时间
Within your programs, there will be times when you need tocompare two dates.One way to compare dates is toconvert the dates to milliseconds since a specific date, such as seconds since
the epoch date (discussed in Tip 366).The Date class getTime method returns the number of millisecondssince the epoch date, midnight GMT, January 1st, 1970.Thefollowing statements illustrate how you can use the getDate method to comparetwo dates:
在你的程序中有时会要求比较两个日期或时间.比较时间的一种办法是将这些时间通统转换成某一时刻后的毫秒数,例如诀窍366中讨论的时代日期时间.Date类中的getTime方法就是能返回从日&#26684;林威治午夜12点以来的毫秒数.以下语句示范了怎样用getDate方法来比较日期:
class CompareDates {
&& public static void main(String arg[])
&&&&& Date now = new Date();
&&&&& Date later = new Date(97, 3, 15);
&&&&& long difference = later.getDate() -now.getDate();
&&&&& System.out.println(Current date:& &#43; now.getHours() &#43;
&&&&&&&& &:& &#43; now.getMinutes());
&&&&& System.out.println(Future date:& &#43; future.getHours() &#43;
&&&&&&&& &:& &#43; future.getMinutes());
&&&&& System.out.println(Difference (ms):& &#43; difference);
368 Measure Code Execution Speed with the getTimeMethod
368 利用getTime方法来检测程序的执行速度
As you examine your programs performance, there may betimes when you want to time a particular section of your code.You can time blocks of code within your programs simply by using thegetTime
method before and after the section of code you want to time.For example, the following statements usethe getTime method to determine how much time the for loops processingconsumes:
当你要检查你的程序的性能时,有时会想要算一算运行程序中某一段代码所需的时间。为此你只需把getTime方法插在你所想考察的那一段代码之前和之后。例如,以下语句是利用getTime方法来确定For循环所耗用的时间:
Date now = newDate();&
long startTime=now.getTime(); // begin time count 开始时间计数
for (long m=0; m &1000000; m&#43;&#43;)
& ; // do whatever time consuming task
now = new Date();
long endTime =now.getTime();& // end the time count 结束时间计数
System.out.println(Milliseconds=&#43; (endTime-startTime));
These statements will display the time it takes the program toperform thefor loop, as follows:
这些语句将显示程序执行循环所用去的时间,如下:
Milliseconds=1616
369 Comparing Dates with after, before, and equals Methods
369 利用after、before、和 equals方法来比较日期
Java provide several methods to compare two Date objects: after, before andequals.The following statements create two Date objects, each with a different date.The statementsthen determine
if one date is before or after the other, or whether they are the same date:
Java提供了比较两个Date对象的几种方法: after、before、equals。以下语句创建两个有不同日期的Date对象,然后再确定一个对象是否在另一对象之前或之后,或者它们是同一个日期:
Date startDate= newDate();
Date endDate= newDate(120, 4, 31);
System.out.println(startDate.toLocaleString());
System.out.println(endDate.toLocaleString());
System.out.println(Isstart date after& &#43;
& startDate.after(endDate));
System.out.println(Isstart date before& &#43;&&
& startDate.before(endDate));
System.out.println(Aredates equal& &#43;startDate.equals(endDate));
These statements will display the following output:
这些语句将产生下列的输出:
Saturday, 31August, :39 AM
Sunday, 31May, :00 AM
Is start date afterfalse
Is start date beforetrue
Are dates equal false
370 Converting String to Date
370 将字符串转换为日期
The Date class provides a very convenient constructor that takesa String representation of a date and converts the string into a Date object byassigning values to the various time and date fields.The
followingstatements illustrate the use of the Date class String-based constructor:
Date类提供了一个非常方便的、用字符串表示日期的构造函数,利用对各种日期和时间域的赋&#20540;,可以将字符串转变成Date对象。以下语句说明了Date类的这种字符串型构造函数的用法:
Date someDate= newDate(&Dec 25, 1996&);
System.out.println(someDate.toLocaleString());
someDate= newDate(&Dec 25,
System.out.println(someDate.toLocaleString());
In this case, the statements successfully convert the twoStrings into Date objects and display the following dates:
这里,语句将字符串转换成Date对象,并显示下面这样的日期:
Wednesday, 25December, :00 AM
Wednesday, 25December, :00 PM
{ kaj what if conversion error occurs ???}
371 Creating a daysBetween Function
371 建立一个计算间隔天数的函数
Because the Date class lets your programs express dates in termsof milliseconds from a known epoch date, you can determine the number ofmilliseconds between two dates very easily.After
youhave the number of milliseconds between dates, you candetermine the number of days between those dates.Thefollowing statements, for example, convert milliseconds to days by dividing the milliseconds by, that is, the numberof milliseconds per day:
由于Date类使你的程序在表示日期时是从一已知的时代日期算起的毫秒数,你可以很容易地确定处于两个日期之间的毫秒数。而有了两个日期之间的毫秒数之后,你就可计算这两个日期之间的天数。为此,只要用一天的毫秒数()来除两个日期之间的毫秒数就可以了。以下语句说明了这一方法:
import java.applet.*;
import java.awt.*;
import java.util.*;
public class Testextends Applet {&&
&& public long days(Date startDate,Date endDate)
&&&&&&& return(Math.abs(endDate.getTime()
&&&&&&&&& startDate.getTime())/);
&& public void init()
&&&&&& Date startDate = new Date(96, 8, 4);
&&&&&& Date endDate = new Date(96, 8, 6);
&&&&&& System.out.println(Diffence =& &#43; days(startDate,endDate));
In this program, the days method takes two Date objects andreturns the number of days between them.
在此程序中,days方法用了两个Date对象,返回的是这两个date之间的天数。
372 Creating a daysInMonth Method
372 建立一个计算一月中天数的方法,daysInMonth
Within your programs, you can use the Date class to determinethe number of days in any month.The followingDaysInMonth method takes a Date object and returns the number of days in thedates
month.The method works by determining how manydays there are from the specified date to the first of the following month.
{以上原文有错!}
在你程序中,你可使用Date类来确定任何一个月的天数。以下的daysInMonth方法以一个Date对象作为输入参数,返回的是这一指定月份所包含的天数。这一方法的实现是计算从包含指定日期的月份的第一天到下一个月的第一天之间有多少天数。
short DaysInMonth(DatethisDate)
&& Date tempDate = new Date();
&& tempDate.setTime(thisDate.getTime());& // copy the date 拷贝日期
&& if (thisDate.getMonth()!= 11)
&&&&&&& tempDate.setMonth(thisDate.getMonth() &#43;1);
&&&& {&&// special case of December 12月份为特殊情况
&&&&&& tempDate.setMonth(0);
&&&&&& tempDate.setYear(thisDate.getYear() &#43;1);
&& tempDate.setDate(1);
&&diff=Math.abs(tempDate.getTime()-thisDate.getTime())/;
&& diff&#43;= thisDate.getDate();
&& return((short)(diff-1));
373 Understanding Different Date Standards
373 弄清不同的日期标准
The basis for standard time throughoutthe world is the meridian at Greenwich, England.You can specify the time for any location in the world in terms ofthe number of hours from Greenwich
Mean Time, or simplyGMT.Java uses midnight GMT,January 1st, 1970 for its epoch date.Java provides methods you can use to express the time based on twotime locations: the time at Greenwich and your local time.Of course, the classes determine the timebased on
your computers clock and time-zone settings.Thus, you must make sure that both your systems time and time-zonesettings are correct.When you need to express the timeand date in terms of GMT, you can use the Date classtoGMTString method.If you need the time
expressed inthe local time, use Date class toLocaleString method.The Date class getTimezoneOffset method determines the localtime-zone offset, which is the number of minutes yourprogram must add to Greenwich Mean Time to give the local time zone.This value
includes the correction,ifnecessary, for daylight savings time.
全世界的基本标准时间是英国&#26684;林威治子午线时间。你可以用从&#26684;林威治平均时间(简记为GMT)开始算起的时数来表示世界上任何一个地区的时间。Java用号午夜12点(GMT)作为时代时间。Java为你提供了两种时间位置表示时间的方法,即&#26684;林威治时间和你的局部地区时间。当然,实际的计算还决定于你的计算机的时钟和时区的设置。因此,你必须保证你的系统时间和时区的设置都正确无误.当你需要用GMT标准表示时间和日期时,你可使用Date类的toGMTString方法,如果你想得到局部地区时间,则你可使用Date类中的toLocaleString方法。Date类中的getTimezoneOffset方法则用来设置时区,它代表你所在的局部地区时间与GMT时间之间相差的分数,在你的程序中只要把这一分数加到GMT时间上,就可得到你所在的局部地区时间。
<span style="color:#FF Java Tips
PAGE7 of numpages 35
Filename jt0375_a
November 24, 1996
Date Class
Date类(日期类)
374 Beware When Relying on Date Formats
374 留心与Date&#26684;式有关的事情
When you work with the Date class object, be aware that Sun hasreported several bugs in the Date class. One bug involves the toString method,which gives different output on different platforms. If your program parses thestring
or relies on the presence of specific fields, you should carefullyverify that the strings contain the text you expect. For example, on a SunSolaris computer, calling the Date class toString method will result in thisoutput:
当你利用Date类对象工作时,必须留心Sun公司已报告的Date类中的几个疏忽。一个疏忽包含在toString方法中,它在不同的平台上会有不同的结果。如果你的程序要分析所得的string,或者依赖于所得string的某些域,则你必须小心验证你所期望的文本字符串。例如,在Sun的Solaris计算机上,调用Date类的toString方法将产生以下结果:
Tue Sep 10 12:22:56PDT 1996
On Microsoft Windows NT and Windows 95, the toString methodproduces the
following date string:
而在Microsoft Windows NT 和 Windows95上,toString方法将生成以下日期字符串:
Tue Sep 10 12:22:561996
375 Using the DOS TZ Environment Variable
375 使用 DOS 环境变量 TZ
If you use a Windows-based system, you can set the time-zonevariable, TZ, by placing a SET command within your systems AUTOEXEC.BAT file.The format of the TZ entry is as follows:
如果你使用基于Windows的系统,你可在AUTOEXEC.BAT中利用SET命令之后加上时区变量TZ来设置时区。TZ的输入&#26684;式如下:
SETTZ=SSS[&#43;/-]h[h][DDD]
The SSS field contains the standard time zone name (such as ESTor PST), and the [&#43;/-]h[h] specifies the difference in hours between thestandard time zone and GMT. Finally, the DDD field specifies the name of thedaylight savings
time zone (such as PDT). The following entry sets the time zonefor the West Coast when daylight savings time is active:
SSS 域中包括标准时区名(如EST 或 PST)和选项[&#43;/-]h[h],后者用来指示标准时区与GMT的时数差。最后,DDD域用来指示夏令时时区名,如PDT。当夏令时生效时,以下参数可用来为西海岸设置时区:
SET TZ=PST8PDT
When daylight savings time is not active, omit the time zonename, as shown:
如果未设置夏令时,则可省去时区名,如:
SET TZ=PST8
If you do not specify a TZ entry, the default is EST5EDT.
如果你不指定TZ参数,则使用的缺省&#20540;为 EST5EDT(美国东部时区)。
Using Arrays to StoreData
利用数组存放时间和日期
376 Understanding Arrays
376 了解数组
Throughout this books tips, you have learned how to createvariables for individual objects. Sometimes, however, you will need tomanipulate a series of related objects within an array object. To do this, youcan use aArrays let
your programs work conveniently with a group of relatedobjects. In short, an array is simply a waylets you to store and access a setof objects of the same type within the same variable. For example, you can usean array to keep track of grades for fifty students
or to store a series offilenames.
Even though Java arrays are similar in syntax to C/C&#43;&#43; arrays,they have subtle differences. In Java, an array is an actual basically anobject that points to a set of other objects or primitive data types. The onlyvisible difference
between arrays and objects is that arrays have a specialsyntax to make them behave like the arrays found in other languages. Unlike Cand C&#43;&#43;, however, Java arrays cannot change in size, and also cannot benor cana program use an out-of-bounds index with a Java
array. Also, you declare andcreate arrays in Java very differently than in C/C&#43;&#43;. The following tips describehow to create and use arrays in Java.
通过本书前面的诀窍你已知道怎样为单个对象创建变量。但是,你有时必需同时处理相关的一系列对象。为了实现这一事情,你可以利用数组,它可使你的程序方便地处理相关的一系列对象。一个数组,简单地说,就是能在同一个变量中存放和引用相同类型的一组对象的方法。例如,你可利用一个数组来保存50个学生的成绩,或存放一系列文件的名称。
Java的数组在语法上和C或C&#43;&#43;数组类&#20284;,但它们有着微妙的差别。在Java中,一个数组从根本上说就是一个指向一组对象或一组原始数据类型的实际对象。数组对象与原始对象之间可以觉察的唯一差别在于,数组具有一种特殊的语法,使它们的行为看上去和其它语言中的数组一样。但与C或C&#43;&#43;不同,Java中的数组不能改变大小,而且在程序中使用时也不允许下标超越它的范围。另外,你在Java中说明和建立数组的方法和C或C&#43;&#43;中所用的也很不相同。以下几个诀窍将描述怎样在Java中建立和使用数组。
377 Declaring an Array in Java
377 在Java中说明(声明)一个数组
As you have learned, creating an object is a two-step process.To start, you must first declare the object. Then, you must make an instance ofthat object. In Java, arrays are objects. Therefore, you must first declare anarray,
and then create it. In Java, you can declare an array in two ways. Thefirst syntax places the bracketbraces [][] on the variable name. The followingcode demonstrates an integer array declaration:
你已知道了,创建一个对象是一个两步的过程。开始,你必须首先说明这个对象。然后,你必须为此对象制造一个实例。在Java中,数组也是对象,所以你必须先要说明一个数组,然后再创建它。在Java中,说明一个数组可以用两种办法。第一种方法是在变量名后加一对或几对括号[]。以下语句是(一维)整型数组的说明方法:
int myarray[];
The alternative declaration syntax places the bracketbraces []on the variable data type. The following code demonstrates the type name:
另一种句法是在变量数据类型后加对括号[]。以下语句是采用这种句法的说明:
Notice that the size of the array is not part of thedeclaration. You define an arrays size when you create the array.
注意,数组的大小不属于说明的一部分内容。你必须在以后创建数组的实例时再来定义数组的大小。
378 Creating an Array of Primitive Data Types
378& 创建一个原始日期类型(Primitive Data Types)数组
In Tip 377, you learned how to declare an array. Your next stepis to create the array object. As you have learned, in Java you create objectswith the new keyword. When you create an array, you follow the new keyword withthe object
type followed by the size of the array in bracketbraces. A primitivearray is an array of one of the primitive numeric, char, or boolean types. Thefollowing statements demonstrate how to create various primitive arraysan arrayof 100 integers.
在诀窍377中,你已知道怎样说明一个数组。你的下一个步骤就是要创建一个数组对象。正如你已所了解的,在 Java中,要建立一个对象要使用新的关键字(keyword)。当你创建数组时,你应在对象类型的新关键字后的一对括号中填写数组的大小。一个原始数组是指由单个数&#20540;或字符或布尔类型组成的数组。以下语句说明了怎样创建包含100个元素的不同类型的数组:
int myarray1[] = newint[100];
double myarray2[] =new double[100];
boolean myarray3[] =new boolean[100];
In this case, the statements do not initialize the contents ofthe arrays. However, by default, Java initializes the primitive numeric datatype arrays to zero and boolean arrays to false.
在本例中,语句没有对数组的内容初始化。但是,按照约定,Java将原始数&#20540;数据类型初始化为0,而将Boolean数组初始化为false。
379 Initializing an Array of Primitive Data Types
379& 初始化一个原始数据类型数组
Just as with C/C&#43;&#43; and other programming languages, you caninitialize numeric arrays when you declare the arrays. When you specify initialvalues within an array declaration, Java performs the new operation and definesthe array
size for you. The following statements demonstrate the declarationand initialization of a numeric array and a boolean array:
如同C或C&#43;&#43;以及许多其它程序设计语言一样,你可以在数组的说明中来初始化数组。当你在数组的说明中指定数组的初&#20540;时,Java执行这一新操作,并且为你确定数组的大小。以下语句说明了一个数&#20540;数组和一个布尔数组的说明和初始化方法:
int myarray1[] = { 1,2, 3, 4, 5 };
boolean myarray2[] = {true, false, true };
In these examples, Java creates onean array object that holdsfive integers and a second array that holds three boolean values. Java alsoinitializes the arrays with the specified values. Notice that you surround thearray values
with braces {}, and separate each value with a comma.
在这一例子中,Java 建立了具有五个整型数的数组对象和具有三个布尔量的另一个数组对象。Java同时用所给出的&#20540;来初识化数组。注意,数组元素要用括号{}括起来,相互之间用一逗号分开。
380 Understanding Array Indexing
380 了解数组的下标记法
Each value of an array is called an array element. To access anarray element, you specify the name of the array with the index of that elementplaced between bracketbraces []. Java array indexing is similar to that ofC/C&#43;&#43;. The
following code demonstrates a loop that cycles through all theelements of an array and displays each value to the screen:
数组中的每一个数据叫数组元素。要存取一个数组的元素,你应指出该数组的名字,并在其后面的一对括号中填入所需元素的索引号(即下标)。Java数组的下标形式和C或C&#43;&#43;类&#20284;。以下语句是一个循环程序,它依次引用一个数组中的每一个元素,并在屏幕上显示了每一个元素的&#20540;:
int myarray[] = { 1,2, 3, 4, 5 };
for (int index = 0;index & 5; index&#43;&#43;)
&& System.println(myarray[index]);
In this example, the size of the array is five. In Java, theindex of the first element of an array is zero, and the last location is thesize of the array minus one. Therefore, to loop through all the members of thearray, the program
uses the loop variable values 0 to 4.
When you index a Java array, Java checks that the index value isgreater than or equal to zero and less than the size of the array. If the indexis less than zero or greater than or equal to the size of the arrayout of thisrange,
then Java will generate an IndexOutOfBoundsException& error and terminate your program. (Anexceptions is how Java flags an error conditions. You will learn about theexceptions in later tips. )
在本例子中,数组的大小是5。在Java中,数组的第一个元素的下标为0,而最后一个元素的下标是数组的大小减1。因此,循环要遍历所有元素,程序的循环变量的取&#20540;应是0到4。
当你用下标引用Java数组时,Java将检查所用下标是否大于、小于或等于数组的大小。如果下标小于0,或大于或等于数组的尺寸,则Java将产生一个指示下标已溢出数组范围的错误:IndexOutOfBoundsException,并终止你的程序。Exception(例外)是Java用于说明各种出错情况的标志。你在今后的一些诀窍中会学到有关的各种Exception。
381 Assigning an Array Element
381 为数组元素赋&#20540;
You have learned how to access an array element. Within yourprograms, you can use an array element just like any other variable. For example,you can use the assignment operator to change the array elements value anywhere within
the class that defines the array. Likewise, you can access theelements value from any location within the class. The following statementsdeclare the array myarray to store five integer values. Then, within the forloop, the program assigns values to the array
elements and then accesses (uses)the elements value within the System.out.println function call:
以上你已了解了怎样存取数组元素。在你的程

我要回帖

更多关于 java编程软件下载 的文章

 

随机推荐