当前位置:编程学习 > JAVA >>

java日期时间类详解

Date 类: 最基础的日期时间类,返回一个相对日期的毫秒数。精确到毫秒,但不支持日期的国际化和分时区显示。
Calender类: 相对于Date更加强大的时间类,是抽象类,提供了常规的日期修改功能和国际化支持。
GregorianCalendar类: 提供处理日期的方法,用于计算日期,是Calendar类的子类,有用的是有个判断闰年的方法。
DateFormat类: 可以接受字符串输入 输出,提供了将日期/时间信息进行格式化处理的功能。
SimpleDateFormat类: 功能更强大的日期时间格式化类,自定义格式化日期和时间。
java.util.Locale类: 描述特定的地理、政治、文化上的地区,Locale对象主要封装了“地区”和“语言种类”两方面 .
使用案列:
1.获取当前时间
public String GetCurTime()//获得当前时间
{
Date now=new Date();
return now.getHours()+":"+now.getMinutes()+":"+now.getSeconds();
}
public String GetCurDate()//获得当前日期
{
Calendar cal=Calendar.getInstance();
return cal.get(Calendar.YEAR)+"年"+(cal.get(Calendar.MONTH)+1)+"月"+cal.get(Calendar.DATE)+"日";
}
2.获取一月前时间
calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
3.获取一年前时间
calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
4.获取相对日期的毫秒数
Calendar calendar = Calendar.getInstance();
long nowTime = calendar.getTime().getTime();
5.转换字符串为日期 www.zzzyk.com
String strDate = "2011-08-13";
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date sDate = sDateFormat.parse(strDate);
6.格式化显示日期型数据
Date dt_in :日期型数据
boolean bShowTimePart_in : 是否显示时间部分
@return String 格式化后的日期格式
*/
public String DoFormatDate(java.util.Date dt_in, boolean bShowTimePart_in) {
if (bShowTimePart_in)
return (new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(dt_in);
else
return (new SimpleDateFormat("yyyy-MM-dd")).format(dt_in);
}
7.判断闰年
8.国际化,信息通常用于在国际化和本地化程序中的地区、语言相关的方式显示日期、数字或文本信息等
public void testLocale(){
Locale defaultLocale = Locale.getDefault(); //当前机器所在的国家和地区
System.out.println(defaultLocale);
System.out.println(defaultLocale.getLanguage()); //英文宿写的语言名
System.out.println(defaultLocale.getCountry()); //英文宿写的国家名
System.out.println(defaultLocale.getDisplayName()); //语言名(国家名)
System.out.println(defaultLocale.getDisplayLanguage()); //语言名
System.out.println(defaultLocale.getDisplayCountry()); //国家名
System.out.println("--------------------------");
}

 

摘自  qcyycom
补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,