首页 > 应用开发 > IT综合 > [转]Java日期操作
是从2个入门资料合并整理的,具体的URL我已经忘了,未经同意就转载 抱歉啦
Java日期概念
应用到的类
java.text.DateFormat
java.util.TimeZone
java.util.Locate
java.util.Date
java.sql.Date(继承自java.util.Date)
Locale类的一个实例通常包含国家和语言信息。其中的每一个部分都是由基于国际标准化组织(ISO)制定的国家代码ISO-3166和语言代码ISO-639的两字符的字符串构成的。
示例:创建两个Locale实例,其中一个对应的是美国英语而另一个对应的是法国法语。
DateExample6.java
-------------------------------------------------------------------------------
import java.util.Locale;
public class DateExample6 {
public static void main(String[] args) {
// Create a locale for the English language in the US.
Locale localeEN = new Locale("en", "US");
System.out.println("Display Name: " + localeEN.getDisplayName());
System.out.println("Country: " + localeEN.getCountry());
System.out.println("Language: " + localeEN.getLanguage());
// Create a locale for the French language in France.
Locale localeFR = new Locale("fr", "FR");
System.out.println("nDisplay Name: " + localeFR.getDisplayName());
System.out.println("Country: " + localeFR.getCountry());
System.out.println("Language: " + localeFR.getLanguage());
// Display the English-US locale in French
System.out.println("nen Display Name in French: " + localeEN.getDisplayName(localeFR));
}
}
-------------------------------------------------------------------------------
getDisplayName()方法显示Locale的一个更易读的文本
在对English Locale对象调用getDisplayName的时候同时传递了French Locale对象。这允许我们选择显示Locale对象所用的语言,让我们用英语显示法语Locale对象的内容。
下面是输出
-------------------------------------------------------------------------------
Display Name: English (United States)
Country: US
Language: en
Display Name: French (France)
Country: FR
Language: fr
en Display Name in French: anglais (tats-Unis)
-------------------------------------------------------------------------------
使用java.util.Locale和java.text.DateFormat类我们就能够格式化日期数据把它显示给在另一个地域的用户,比方法国。
示例:
DateExample7.java
-------------------------------------------------------------------------------
import java.util.Locale;
import java.util.Date;
import java.text.DateFormat;
public class DateExample7 {
public static void main(String[] args) {
// Get the current system date and time.
Date date = new Date();
// Get a France locale using a Locale constant.
Locale localeFR = Locale.FRANCE;
// Create an English/US locale using the constructor.
Locale localeEN = new Locale("en", "US" );
// Get a date time formatter for display in France.
DateFormat fullDateFormatFR = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL,localeFR);
// Get a date time formatter for display in the U.S.
DateFormat fullDateFormatEN = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL,localeEN);
System.out.println("Locale: " + localeFR.getDisplayName());
System.out.println(fullDateFormatFR.format(date));
System.out.println("Locale: " + localeEN.getDisplayName());
System.out.println(fullDateFormatEN.format(date));
}
}
-------------------------------------------------------------------------------
这个例子的输出是:注意这个输出包括了时区信息:GMT-04:00 和 PM EDT。这个时区是人系统的时区设置里捕获的。你可以看见,日期是以那个地区的用户期望的格式显示的。
-------------------------------------------------------------------------------
Locale: French (France)
vendredi 5 octobre 2001 21 h 05 GMT-04:00
Locale: English (United States)
Friday, October 5, 2001 9:05:54 PM EDT
-------------------------------------------------------------------------------
TimeZone类,即java.util.TimeZone类的实例包含了一个与格林威治标准时间(GMT)相比较得出的以微秒为单位的时区偏移量,而且它还处理夏令时。要获得一个所有支持的进区的列表,你可以使用方法TimeZone.getAvailableIDs,它将返回一个包含了所有进区ID的字符串数组。要知道关于TimeZone类的更多细节,可以参看Sun公司的Web站点。
示例:为了演示这个概念,我们将创建三个时区对象。第一个对象将使用getDefault从系统时钟返回时区数据;第二个和第三个对象将传入一个时区字符串ID。
DateExample8.java
-------------------------------------------------------------------------------
import java.util.TimeZone;
import java.util.Date;
import java.text.DateFormat;
import java.util.Locale;
public class DateExample8 {
public static void main(String[] args) {
// Get the system time zone.
TimeZone timeZoneFL = TimeZone.getDefault();
System.out.println("n" + timeZoneFL.getDisplayName());
System.out.println("RawOffset: " + timeZoneFL.getRawOffset());
System.out.println("Uses daylight saving: " + timeZoneFL.useDaylightTime());
TimeZone timeZoneLondon = TimeZone.getTimeZone("Europe/London");
System.out.println("n" + timeZoneLondon.getDisplayName());
System.out.println("RawOffset: " + timeZoneLondon.getRawOffset());
System.out.println("Uses daylight saving: " + timeZoneLondon.useDaylightTime());
TimeZone timeZoneParis = TimeZone.getTimeZone("Europe/Paris");
System.out.println("n" + timeZoneParis.getDisplayName());
System.out.println("RawOffset: " + timeZoneParis.getRawOffset());
System.out.println("Uses daylight saving: " + timeZoneParis.useDaylightTime());
}
}
-------------------------------------------------------------------------------
其输出如下:
正如你所看见的,TimeZone对象给我们的是原始的偏移量,也就是与GMT相差的微秒数,而且还会告诉我们这个时区是否使用夏令时。有个这个信息,我们就能够继续将时区对象和日期格式化器结合在一起在其它的时区和其它的语言显示时间了。
-------------------------------------------------------------------------------
Eastern Standard Time
RawOffset: -18000000
Uses daylight saving: true
GMT+00:00
RawOffset: 0
Uses daylight saving: true
Central European Standard Time
RawOffset: 3600000
Uses daylight saving: true
-------------------------------------------------------------------------------
示例:让我们来看一个结合了国际化显示,时区和日期格式化的例子。表D为一个在迈阿密和巴黎拥有办公室的公司显示了当前的完整日期和时间。对于迈阿密的办公室,我们将在每个办公室里用英语显示完整的日期和时间。对于巴黎的办公室,我们将用法语显示完整的当前日期和时间。
DateExample9.java
-------------------------------------------------------------------------------
import java.util.TimeZone;
import java.util.Date;
import java.util.Locale;
import java.text.DateFormat;
public class DateExample9 {
public static void main(String[] args) {
Locale localeEN = Locale.US;
Locale localeFrance = Locale.FRANCE;
TimeZone timeZoneMiami = TimeZone.getDefault();
TimeZone timeZoneParis = TimeZone.getTimeZone("Europe/Paris");
DateFormat dateFormatter = DateFormat.getDateTimeInstance(
DateFormat.FULL,
DateFormat.FULL,
localeEN);
DateFormat dateFormatterParis = DateFormat.getDateTimeInstance(
DateFormat.FULL,
DateFormat.FULL,
localeFrance);
Date curDate = new Date();
System.out.println("Display for Miami office.");
// Print the Miami time zone display name in English
System.out.println(timeZoneMiami.getDisplayName(localeEN));
// Set the time zone of the dateFormatter to Miami time zone.
dateFormatter.setTimeZone(timeZoneMiami);
// Print the formatted date.
System.out.println(dateFormatter.format(curDate));
// Set the time zone of the date formatter to Paris time zone.
dateFormatter.setTimeZone(timeZoneParis);
// Print the Paris time zone display name in English.
System.out.println(timeZoneParis.getDisplayName(localeEN));
// Print the Paris time in english.
System.out.println(dateFormatter.format(curDate));
System.out.println("nDisplay for Paris office.");
// Print the Miami time zone display name in French
System.out.println(timeZoneMiami.getDisplayName(localeFrance));
// Set the timezone of the
// dateFormatterParis to Miami time zone.
dateFormatterParis.setTimeZone(timeZoneMiami);
// Print the formatted date in French.
System.out.println(dateFormatterParis.format(curDate));
// Set the timezone of the date formatter to Paris time zone.
dateFormatterParis.setTimeZone(timeZoneParis);
// Print the Paris time zone display name in French.
System.out.println(timeZoneParis.getDisplayName(localeFrance));
// Print the Paris time in French.
System.out.println(dateFormatterParis.format(curDate));
}
}
-------------------------------------------------------------------------------
这个例子的输出是:
Display for Miami office.
Eastern Standard Time
Friday, October 5, 2001 10:28:02 PM EDT
Central European Standard Time
Saturday, October 6, 2001 4:28:02 AM CEST
Display for Paris office.
GMT-05:00
vendredi 5 octobre 2001 22 h 28 GMT-04:00
GMT+01:00
samedi 6 octobre 2001 04 h 28 GMT+02:00
-------------------------------------------------------------------------------
在一个SQL数据库中保存和提取日期数据我们将要使用的下一个类是java.sql.Date,它是java.util.Date的子类但它使用了Java数据库连接(JDBC)方法
。让我们来看一个简单的只有一个表单--LAST_ACCESS的ORACLE数据库,它是用下面的SQL创建的:
create table LAST_ACCESS (
LAST_HIT date
);
这个表单只有一个记录,用下面的插入语句创建:
insert into LAST_ACCESS values (Sysdate);
-------------------------------------------------------------------------------
示例:表E演示了如何修改和提取LAST_HIT数据库域。
DateExample10.java
-------------------------------------------------------------------------------
import java.sql.*;
import java.text.DateFormat;
import java.util.Date;
public class DateExample10 {
public static void main(String[] args) {
// Get a full date formatter.
DateFormat dateFormatter = DateFormat.getDateTimeInstance(
DateFormat.FULL,
DateFormat.FULL);
// Get the system date and time.
java.util.Date utilDate = new Date();
// Convert it to java.sql.Date
java.sql.Date date = new java.sql.Date(utilDate.getTime());
// Display the date before storing.
System.out.println(dateFormatter.format(date));
// Save the date to the database.
setLastHit(date);
// Get the date from the database.
Date dateFromDB = getLastHit();
// Display the date from the database.
System.out.println(dateFormatter.format(dateFromDB));
}
public static void setLastHit(java.sql.Date date) {
try {
// Load the class.
Class.forName("oracle.jdbc.driver.OracleDriver");
// Get a connection.
Connection connection = DriverManager.getConnection(
// Database URL
"jdbc:oracle:thin:@localhost:1521:buzz2",
"web_site", // Username
"web_site"); // Password
try {
// Get a prepared statement fromthe connection
// specifying the update SQL.
PreparedStatement ps = connection.prepareStatement("update LAST_ACCESS set LAST_HIT=?");
try {
// set the date letting JDBC to the work of
// formatting the SQL appropriately.
ps.setDate(1, date);
// Execute the update statement.
int iRowsUpdated = ps.executeUpdate();
System.out.println("Rows updated: " + iRowsUpdated);
} finally {
ps.close();
}
} finally {
connection.close();
}
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
}
public static java.sql.Date getLastHit() {
java.sql.Date returnDate = null;
try {
// Load the driver class.
Class.forName("oracle.jdbc.driver.OracleDriver");
// Get the connection.
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:buzz2",
"web_site", "web_site");
try {
// Get the prepared statement specifying the
// select SQL.
PreparedStatement ps = connection.prepareStatement("select LAST_HIT from LAST_ACCESS");
try {
// Execute the SQL and get the ResultSet object.
ResultSet rs = ps.executeQuery();
try {
// Retreive the record.
if (rs.next()){
Date=rs.getDate();
} else {
System.out.println("Did not get last hit.");
}
} finally {
rs.close();
}
} finally {
ps.close();
}
} finally {
connection.close();
}
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
return returnDate;
}
}
-------------------------------------------------------------------------------
这个例子的输出如下:
-------------------------------------------------------------------------------
Friday, October 5, 2001 10:42:34 PM EDT
Rows updated: 1
Successfully retrieved last hit.
Friday, October 5, 2001 12:00:00 AM EDT
-------------------------------------------------------------------------------
虽然这个例子没有为保存和提取日期数据提供性能上优良的方法,但它确实示范了如何为一条更新和删除语句将Java日期数据转换成SQL日期数据。从一个java.util.Date对象设置Oracle date数据域的过程是由以下的语句处理的:
ps.setDate(1, date);
它是我们预定义语句接口java.sql.PreparedStatement.setDate 的一个方法。
这行代码出现在我们的setLastHit方法里。它将Java以微秒为单位的长整型日期值转换成ORACLE的SQL日期格式。当我们能够在getLastHit方法里用java.sql.PreparedStatement.getDate从数据库取得日期数据的时候这种转换就能够完成。
你还应该注意到只有日期被设置了。小时,分钟,秒,和微秒都没有包括在从Java日期数据到SQL日期数据的转换过程中。
Java日期从1970年1月1日起的毫秒的数量表示日期。也就是说,例如,1970年1月2日,是在1月1日后的86,400,000毫秒。同样的,1969年12月31日是在1970年1月1日前86,400,000毫秒。Java的Date类使用long类型纪录这些毫秒值.因为long是有符号整数,所以日期可以在1970年1月1日之前,也可以在这之后。Long类型表示的最大正值和最大负值可以轻松的表示290,000,000年的时间,这适合大多数人的时间要求。
java.util.Date 类
Date类可以在java.util包中找到,用一个long类型的值表示一个指定的时刻。它的一个有用的构造函数是Date(),它创建一个表示创建时刻的对象。getTime()方法返回Date对象的long值。在下面的程序中,我使用Date()构造函数创建一个表示程序运行时刻的对象,并且利用getTime()方法找到这个日期代表的毫秒数量:
Now.java
-------------------------------------------------------------------------------
import java.util.*;
public class Now {
public static void main(String[] args) {
Date now = new Date();
long nowLong = now.getTime();
System.out.println("Value is " + nowLong);
}
}
-------------------------------------------------------------------------------
当我运行这个程序后,我得到972,568,255,150.快速确认一下这个数字,起码在一个合理的范围:它不到31年,这个数值相对1970年1月1日到我写这篇文章的时间来说,是合理的。计算机是这个毫秒值表示时间,人们可不愿意说" 我将在996,321,998,34见到你。"幸运的是,Java提供了一个转换Date对象到字符串的途径,表示成传统的形式。我们在下一节讨论DateFormat类,它直观的建立日期字符串。
java.text.DateFormat 类
DateFormat类的一个目标是建立一个人们能够识别的字符串。然而,因为语言的差别,不是所有的人希望看到严格的相同格式的日期。法国人更喜欢看到"25 decembre 2000,",但是美国人习惯看到"December 25,2000.",所以一个DateFormat的实例创建以后,这个对象包含了日期的显示格式的信息。如果使用用户电脑区域设置缺省的格式,你可以象下面那样,创建DateFormat对象,使用getDateInstance()方法:
DateFormat df = DateFormat.getDateInstance();
DateFormat类在java.text包中可以找到。
转换成字符串
你可以使用format()方法转换Date对象为一个字符串。下面的示例程序说明了这个问题:
NowString.java
-------------------------------------------------------------------------------
import java.util.*;
import java.text.*;
public class NowString {
public static void main(String[] args) {
Date now = new Date();
DateFormat df = DateFormat.getDateInstance();
String s = df.format(now);
System.out.println("Today is " + s);
}
}
-------------------------------------------------------------------------------
在上面的代码中,展示了没有参数,使用缺省格式的getDateInstance()方法。Java还提供了几个选择日期格式,你可以通过使用重载的getDateInstance(int style)获得。出于方便的原因,DateFormat提供了几种预置的常量,你可以使用这些常量参数。下面是几个SHORT, MEDIUM, LONG, 和FULL类型的示例:
StyleDemo.java
-------------------------------------------------------------------------------
import java.util.*;
import java.text.*;
public class StyleDemo {
public static void main(String[] args) {
Date now = new Date();
DateFormat df = DateFormat.getDateInstance();
DateFormat df1 = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat df2 = DateFormat.getDateInstance(DateFormat.MEDIUM);
DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG);
DateFormat df4 = DateFormat.getDateInstance(DateFormat.FULL);
String s = df.format(now);
String s1 = df1.format(now);
String s2 = df2.format(now);
String s3 = df3.format(now);
String s4 = df4.format(now);
System.out.println("(Default) Today is " + s);
System.out.println("(SHORT) Today is " + s1);
System.out.println("(MEDIUM) Today is " + s2);
System.out.println("(LONG) Today is " + s3);
System.out.println("(FULL) Today is " + s4);
}
}
-------------------------------------------------------------------------------
程序输出如下:
-------------------------------------------------------------------------------
(Default) Today is Nov 8, 2000
(SHORT) Today is 11/8/00
(MEDIUM) Today is Nov 8, 2000
(LONG) Today is November 8, 2000
(FULL) Today is Wednesday, November 8, 2000
-------------------------------------------------------------------------------
同样的程序,在我的电脑上使用缺省设置运行后,改变区域设置为瑞典,输出如下:
-------------------------------------------------------------------------------
(Default) Today is 2000-nov-08
(SHORT) Today is 2000-11-08
(MEDIUM) Today is 2000-nov-08
(LONG) Today is den 8 november 2000
(FULL) Today is den 8 november 2000
-------------------------------------------------------------------------------
从这里,你能看到,瑞典的月份不是大写的(虽然November还是november).还有,LONG和FULL版本在瑞典语中是一样的,但是美国英语却不同。另外,有趣的是,瑞典语单词的星期三,onsdag,没有包含在FULL日期里,英语却包括。
注意你能够使用getDateInstance()方法改变DateFormat实例的语种;但是,在上面的例子中,是通过改变Windows98的控制面板的区域设置做到的。不同的地方的区域设置不同,结果就不同,这样有好处,也有不足,Java程序员应该了解这些。一个好处是Java程序员可以只写一行代码就可以显示日期,而且世界不同地区的电脑运行同样的程序会有不用的日期格式。但是这也是一个缺点,当程序员希望显示同一种格式的时--这也有可取之处,举例来说,在程序中混合输出文本和日期,如果文本是英文,我们就不希望日期格式是其他的格式,象德文或是西班牙文。如果程序员依靠日期格式编程,日期格式将根据运行程序所在电脑的区域设置不用而不同。
解析字符串
通过parse()方法,DateFormat能够以一个字符串创立一个Date对象。这个方法能抛出ParseException异常,所以你必须使用适当的异常处理技术。下面的例子程序通过字符串创建Date对象:
ParseExample.java
-------------------------------------------------------------------------------
import java.util.*;
import java.text.*;
public class ParseExample {
public static void main(String[] args) {
String ds = "November 1, 2000";
DateFormat df = DateFormat.getDateInstance();
try {
Date d = df.parse(ds);
}
catch(ParseException e) {
System.out.println("Unable to parse " + ds);
}
}
}
-------------------------------------------------------------------------------
在创建一个任意的日期时parse()方法很有用。我将通过另一种方法创建一个任意得日期。同时,你将看到怎样进行基本日期计算,例如计算90天后的另一天。你可以使用GregorianCalendar类来完成这个任务。
java.text.GregorianCalendar 类
创建一个代表任意日期的一个途径使用GregorianCalendar类的构造函数,它包含在java.util包中:
GregorianCalendar(int year, int month, int date)
注意月份的表示,一月是0,二月是1,以此类推,是12月是11。因为大多数人习惯于使用单词而不是使用数字来表示月份,这样程序也许更易读,父类Calendar使用常量来表示月份:JANUARY, FEBRUARY,等等。所以,创建Wilbur 和 Orville制造第一架动力飞机的日期(December 17, 1903),你可以使用:
GregorianCalendar firstFlight = new GregorianCalendar(1903, Calendar.DECEMBER, 17);
出于清楚的考虑,你应该使用前面的形式。但是,你也应该学习怎样阅读下面的短格式。下面的例子同样表示December 17,1903(记住,在短格式中,11表示December)
GregorianCalendar firstFlight = new GregorianCalendar(1903, 11, 17);
在上一节中,你学习了转换Date对象到字符串。这里,你可以做同样的事情;但是首先,你需要将GregorianCalendar对象转换到Date。要做到这一点,你可以使用getTime()方法,从它得父类Calendar继承而来。GetTime()方法返回GregorianCalendar相应的Date对象。你能够创建GregorianCalendar对象,转换到Date对象,得到和输出相应的字符串这样一个过程。下面是例子:
Flight.java
-------------------------------------------------------------------------------
import java.util.*;
import java.text.*;
public class Flight {
public static void main(String[] args) {
GregorianCalendar firstFlight = new GregorianCalendar(1903, Calendar.DECEMBER, 17);
Date d = firstFlight.getTime();
DateFormat df = DateFormat.getDateInstance();
String s = df.format(d);
System.out.println("First flight was " + s);
}
}
-------------------------------------------------------------------------------
有时候创建一个代表当前时刻的GregorianCalendar类的实例是很有用的。你可以简单的使用没有参数的GregorianCalendar构造函数,象这样:
GregorianCalendar thisday = new GregorianCalendar();
一个输出今天日期的例子程序,使用GregorianCalendar对象:
Today.java
-------------------------------------------------------------------------------
import java.util.*;
import java.text.*;
class Today {
public static void main(String[] args) {
GregorianCalendar thisday = new GregorianCalendar();
Date d = thisday.getTime();
DateFormat df = DateFormat.getDateInstance();
String s = df.format(d);
System.out.println("Today is " + s);
}
}
-------------------------------------------------------------------------------
注意到,Date()构造函数和GregorianCalendar()构造函数很类似:都创建一个对象,条件简单,代表今天。
日期处理
GregorianCalendar类提供处理日期的方法。一个有用的方法是add().使用add()方法,你能够增加象年,月数,天数到日期对象中。要使用add()方法,你必须提供要增加的字段,要增加的数量。一些有用的字段是DATE, MONTH, YEAR, 和 WEEK_OF_YEAR。下面的程序使用add()方法计算未来80天的一个日期。在Jules的<环球80天>是一个重要的数字,使用这个程序可以计算Phileas Fogg从出发的那一天1872年10月2日后80天的日期:
World.java
-------------------------------------------------------------------------------
import java.util.*;
import java.text.*;
public class World {
public static void main(String[] args) {
GregorianCalendar worldTour = new GregorianCalendar(1872, Calendar.OCTOBER, 2);
worldTour.add(GregorianCalendar.DATE, 80);
Date d = worldTour.getTime();
DateFormat df = DateFormat.getDateInstance();
String s = df.format(d);
System.out.println("80 day trip will end " + s);
}
}
-------------------------------------------------------------------------------
这个例子是想象的,但在一个日期上增加天数是一个普遍的操作:影碟可以租3天,图书馆可以借书21天,商店经常需要将购买的物品在30天内卖出。下面的程序演示了使用年计算:
Mortgage.java
-------------------------------------------------------------------------------
import java.util.*;
import java.text.*;
public class Mortgage {
public static void main(String[] args) {
GregorianCalendar mortgage = new GregorianCalendar(1997, Calendar.MAY, 18);
mortgage.add(Calendar.YEAR, 15);
Date d = mortgage.getTime();
DateFormat df = DateFormat.getDateInstance();
String s = df.format(d);
System.out.println("15 year mortgage amortized on " + s); }
}
-------------------------------------------------------------------------------
add()一个重要的副作用是它改变的原来的日期。有时候,拥有原始日期和修改后的日期很重要。不幸的是,你不能简单的创建一个GregorianCalendar对象,设置它和原来的相等(equal)。原因是两个变量指向同一个Date()对象地址。如果Date对象改变,两个变量就指向改变后的日期对象。代替这种做法,应该创建一个新对象。下面的程序示范了这种做法:
ThreeDates.java
-------------------------------------------------------------------------------
import java.util.*;
import java.text.*;
public class ThreeDates {
public static void main(String[] args) {
GregorianCalendar gc1 = new GregorianCalendar(2000, Calendar.JANUARY, 1);
GregorianCalendar gc2 = gc1;
GregorianCalendar gc3 = new GregorianCalendar(2000, Calendar.JANUARY, 1);
//Three dates all equal to January 1, 2000
gc1.add(Calendar.YEAR, 1);
file://gc1 and gc2 are changed
DateFormat df = DateFormat.getDateInstance();
Date d1 = gc1.getTime();
Date d2 = gc2.getTime();
Date d3 = gc3.getTime();
String s1 = df.format(d1);
String s2 = df.format(d2);
String s3 = df.format(d3);
System.out.println("gc1 is " + s1);
System.out.println("gc2 is " + s2);
System.out.println("gc3 is " + s3);
}
}
-------------------------------------------------------------------------------
程序运行后,gc1和gc2被变成2001年(因为两个对象指向同一个Date,而Date已经被改变了)。对象gc3指向一个单独的Date,它没有被改变。
计算复习日期在这节,你将看到一个依据现实世界的例子。这个详细的程序计算过去一个具体的日期。例如,你阅读这篇文章,你想要记住一个印象深刻的知识点。如果你没有照片一样的记忆力,你就要定期的复习这些新资料,这将帮助你记住它。关于复习系统,Kurt Hanks 和 Gerreld L. Pulsipher在他们的< Five Secrets to Personal Productivity个人能力的5个秘密>中有讨论,建议看过第一眼后马上回顾一下,然后是1天后,1个星期后,1个月后,3个月后,1年后。我的这篇文章,你要马上回顾一下,从现在算起,再就是明天,然后是1个星期,1个月,3个月,1年后。我们的程序将计算这些日期。
这个程序非常有用的,它将是PIM(Personal Information Manager个人信息管理器)的一个组成部分,并将确定复习时间。在下面的程序中,getDates()方法对一个返回日期数组(复习日期)的电子软件很有用。另外,你可以返回单独的一个日期,使用getFirstDay(),getOneDay(),getOneWeek(),getOnMonth()和getOneYear().当时间范围超出这个PIM的ReviewDates的计算范围时ReviewDates类演示了怎样计算时间段。现在,你可以容易的修改它用来处理你需要的时间段,象图书馆借书,录影带租赁和抵押计算。首先,ReviewDates类显示在下面:
ReviewDates.java
-------------------------------------------------------------------------------
import java.util.*;
import java.text.*;
public class ReviewDates {
private GregorianCalendar firstDay, oneDay, oneWeek, oneMonth, oneQuarter, oneYear;
final int dateArraySize = 6;
ReviewDates(GregorianCalendar gcDate) {
int year = gcDate.get(GregorianCalendar.YEAR);
int month = gcDate.get(GregorianCalendar.MONTH);
int date = gcDate.get(GregorianCalendar.DATE);
firstDay = new GregorianCalendar(year, month, date);
oneDay = new GregorianCalendar(year, month, date);
oneWeek = new GregorianCalendar(year, month, date);
oneMonth = new GregorianCalendar(year, month, date);
oneQuarter = new GregorianCalendar(year, month, date);
oneYear = new GregorianCalendar(year, month, date);
oneDay.add(GregorianCalendar.DATE, 1);
oneWeek.add(GregorianCalendar.DATE, 7);
oneMonth.add(GregorianCalendar.MONTH, 1);
oneQuarter.add(GregorianCalendar.MONTH, 3);
oneYear.add(GregorianCalendar.YEAR, 1);
}
ReviewDates() {
this(new GregorianCalendar());
}
public void listDates() {
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
Date startDate = firstDay.getTime();
Date date1 = oneDay.getTime();
Date date2 = oneWeek.getTime();
Date date3 = oneMonth.getTime();
Date date4 = oneQuarter.getTime();
Date date5 = oneYear.getTime();
String ss = df.format(startDate);
String ss1 = df.format(date1);
String ss2 = df.format(date2);
String ss3 = df.format(date3);
String ss4 = df.format(date4);
String ss5 = df.format(date5);
System.out.println("Start date is " + ss);
System.out.println("Following review dates are:");
System.out.println(ss1);
System.out.println(ss2);
System.out.println(ss3);
System.out.println(ss4);
System.out.println(ss5);
System.out.println();
}
public GregorianCalendar[] getDates() {
GregorianCalendar[] memoryDates = new GregorianCalendar[dateArraySize];
memoryDates[0] = firstDay;
memoryDates[1] = oneDay;
memoryDates[2] = oneWeek;
memoryDates[3] = oneMonth;
memoryDates[4] = oneQuarter;
memoryDates[5] = oneYear;
return memoryDates;
}
public GregorianCalendar getFirstDay() {
return this.firstDay;
}
public GregorianCalendar getOneDay() {
return this.oneDay;
}
public GregorianCalendar getOneWeek() {
return this.oneWeek;
}
public GregorianCalendar getOneMonth() {
return this.oneMonth;
}
public GregorianCalendar getOneQuarter() {
return this.oneQuarter;
}
public GregorianCalendar getOneYear() {
return this.oneYear;
}
}
-------------------------------------------------------------------------------
下面是使用ReviewDates类列出复习日期的例子程序:
-------------------------------------------------------------------------------
import java.util.*;
public class ShowDates {
public static void main(String[] args) {
ReviewDates rd = new ReviewDates();
rd.listDates();
GregorianCalendar gc = new GregorianCalendar(2001, Calendar.JANUARY, 15);
ReviewDates jan15 = new ReviewDates(gc);
jan15.listDates();
}
}
-------------------------------------------------------------------------------
总结
这篇文章介绍了关于日期处理的3个重要的类:Date,DateFormat,GregorianCalendar.这些类让你创建日期,转换成字符串,和计算日期基本元素。处理Java中的日期问题,这篇文章只是冰山一角。可是,我在这里介绍的类和方法不仅仅是你学习高级技术的跳板,这些类和方法本身就可以处理很多通常的日期相关的任务。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/7199667/viewspace-915321/ ,如需转载,请注明出处,否则将追究法律责任。