当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
2015年计算机二级考试JAVA知识点整理(28)
发布时间:2010/12/12 18:27:54 来源:城市学习网 编辑:ziteng
  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日”的格式。代码在上例中的黑体部分。
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved