设为首页 加入收藏

TOP

2011年计算机二级考试JAVA知识点整理(28)
2014-10-31 22:15:09 】 浏览:254
Tags:2011年 计算机 二级 考试 JAVA 知识点 整理

  1.1.4 与时间有关的类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日”的格式。代码在上例中的黑体部分。


  编辑推荐:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇2011年计算机二级考试JAVA知识点.. 下一篇2011年计算机二级考试JAVA知识点..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目