与时间有关的类Date,DateFormat,Calendar

Date类用于表示日期和时间。它没考虑国际化问题,所以又设计了另外两个类。

Calendar类:

主要是进行日期字段之间的相互操作。

编程实例:计算出距当前日期时间315天后的日期时间,并使用”xxxx年xx月xx日xx小时:xx分:xx秒”的格式输出。

import java.util.*;

import java.text.SimpleDateFormat; //由于simpledateformat和dateformat在这个包中

public class TestCalendar

{

public static void main(String[] args)

{

Calendar cl=Calendar.getInstance(); //创建一个实例

System.out.println(cl.get(Calendar.YEAR)+"年"+cl.get(cl.MONTH)+"月"+cl.get(cl.DAY_OF_MONTH)+"日 "+cl.get(cl.HOUR)+":"+cl.get(cl.MINUTE)+":"+cl.get(cl.SECOND));

/*

使用get方法来取得日期中的年月日等等,参数为类中的常数,可以直接使用类名调用常数,也可以使用对象名。

*/

cl.add(cl.DAY_OF_MONTH,315);

//加上315天,使用add方法,第一个参数为单位,也是常数。

System.out.println(cl.get(Calendar.YEAR)+"年"+cl.get(cl.MONTH)+"月"+cl.get(cl.DAY_OF_MONTH)+"日 "+cl.get(cl.HOUR)+":"+cl.get(cl.MINUTE)+":"+cl.get(cl.SECOND));

SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd"); //定义了格式

SimpleDateFormat sdf2=new SimpleDateFormat("yyyy年MM月dd日"); //定义了格式

try

{

Date d=sdf1.parse("2003-03-15"); //将字符串强制转换成这种格式,使用parse()

System.out.println(sdf2.format(d));将格式1的日期转换成格式2,使用format()

}

catch(Exception e)

{

e.printStackTrace();

}

}

}

编程实例:将“2002-03-15“格式的日期转换成“2003年03月15日”的格式。代码在上例中的黑体部分。

 

猜你喜欢

转载自www.cnblogs.com/borter/p/9434287.html