Java中的日期处理工具DateTime

 

在java中,可以使用joda提供的类和方法处理。
首先,在java中有两个和日期相关的对象:java.util.Date和java.util.Calendar
Date的常用方式:

Date jdkDate = new Date();

int year = jdkDate.getYear();
int month = jdkDate.getMonth();
int day = jdkDate.getDate();
int hour = jdkDate.getHours();
int minute = jdkDate.getMinutes();
int second = jdkDate.getSeconds();

jdkDate = new Date(year, month, day, hour, minute, second);

DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String dateStr =format.format(jdkDate);
		
System.out.println(dateStr);

 Calendar的常用方式:

Calendar calendar = Calendar.getInstance();
calendar.set(2000, Calendar.JANUARY, 1, 0, 0, 0);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

Date jdkDate = calendar.getTime();

String dateStr = format.format(jdkDate);

System.out.println(dateStr);

 但是这两个对象处理日期的时候,都有点麻烦。我们可以利用第三方的对象处理日期时间。
DateTime的常用方式:

// 新建一个时间,然后对该时间操作,并且格式化输出
DateTime dateTime = new DateTime(2011, 11, 11, 11, 11, 11);
dateTime = dateTime.plusDays(2);
dateTime = dateTime.plusHours(2);
dateTime = dateTime.plusYears(2);
System.out.println(dateTime.toString("yy/MM/dd HH:mm:ss EE"));

//一当前时间点,新建一个时间,
dateTime = new DateTime();
dateTime = dateTime.minusSeconds(1);
dateTime = dateTime.minusMinutes(1);
dateTime = dateTime.minusHours(1);
System.out.println(dateTime.toString("yy/MM/dd HH:mm:ss EE"));

//DateTime转换为Calendar
Calendar calendar = dateTime.toCalendar(new Locale("zh", "ZH"));
System.out.println(calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-" + calendar.get(Calendar.DAY_OF_MONTH));

//DateTime转换为jdk的Date
DateFormat df = null;
Date jkdDate = dateTime.toDate();
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(jkdDate));

 当然,这只是一个最常用的DateTime类的最简单的用法,还有其他的类的其他用法。

我个人觉得这个东西好用的最大特点是可以和jdk中的Date和Calendar互相转换,提高了他的可用性。

 

下载地址:http://sourceforge.net/projects/joda-time/files/joda-time/2.0/

更专业的讲解:http://www.ibm.com/developerworks/cn/java/j-jodatime.html

你可能感兴趣的:(java,Date)