欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java日期时间使用方法汇总

程序员文章站 2024-03-08 22:06:46
一、java中的日期概述 日期在java中是一块非常复杂的内容,对于一个日期在不同的语言国别环境中,日期的国际化,日期和时间之间的转换,日期的加减运算,日期的展示格式都是...

一、java中的日期概述
日期在java中是一块非常复杂的内容,对于一个日期在不同的语言国别环境中,日期的国际化,日期和时间之间的转换,日期的加减运算,日期的展示格式都是非常复杂的问题。 

在java中,操作日期主要涉及到一下几个类: 
1、java.util.date
        类 date 表示特定的瞬间,精确到毫秒。从 jdk 1.1 开始,应该使用 calendar 类实现日期和时间字段之间转换,使用 dateformat 类来格式化和分析日期字符串。date 中的把日期解释为年、月、日、小时、分钟和秒值的方法已废弃。 
2、java.text.dateformat(抽象类)
        dateformat 是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并分析日期或时间。日期/时间格式化子类(如 simpledateformat)允许进行格式化(也就是日期 -> 文本)、分析(文本-> 日期)和标准化。将日期表示为 date 对象,或者表示为从 gmt(格林尼治标准时间)1970 年,1 月 1 日 00:00:00 这一刻开始的毫秒数。 
3、java.text.simpledateformat(dateformat的直接子类)
        simpledateformat 是一个以与语言环境相关的方式来格式化和分析日期的具体类。它允许进行格式化(日期 -> 文本)、分析(文本 -> 日期)和规范化。
        simpledateformat 使得可以选择任何用户定义的日期-时间格式的模式。但是,仍然建议通过 dateformat 中的 gettimeinstance、getdateinstance 或 getdatetimeinstance 来新的创建日期-时间格式化程序。
4、java.util.calendar(抽象类)
        calendar 类是一个抽象类,它为特定瞬间与一组诸如 year、month、day_of_month、hour 等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。瞬间可用毫秒值来表示,它是距历元(即格林威治标准时间 1970 年 1 月 1 日的 00:00:00.000,格里高利历)的偏移量。
        与其他语言环境敏感类一样,calendar 提供了一个类方法 getinstance,以获得此类型的一个通用的对象。calendar 的 getinstance 方法返回一个 calendar 对象,其日历字段已由当前日期和时间初始化。
5、java.util.gregoriancalendar(calendar的直接子类)
        gregoriancalendar 是 calendar 的一个具体子类,提供了世界上大多数国家使用的标准日历系统。
        gregoriancalendar 是一种混合日历,在单一间断性的支持下同时支持儒略历和格里高利历系统,在默认情况下,它对应格里高利日历创立时的格里高利历日期(某些国家是在 1582 年 10 月 15 日创立,在其他国家要晚一些)。可由调用方通过调用 setgregorianchange() 来更改起始日期。

二、java.util.date的使用 
1、java.util.date的api简介
类 java.util.date 表示特定的瞬间,精确到毫秒。提供了很多的方法,但是很多已经过时,不推荐使用,下面仅仅列出没有过时的方法: 
构造方法摘要
-------------
date()
          分配 date 对象并用当前时间初始化此对象,以表示分配它的时间(精确到毫秒)。
date(long date)
          分配 date 对象并初始化此对象,以表示自从标准基准时间(称为“历元(epoch)”,即 1970 年 1 月 1 日 00:00:00 gmt)以来的指定毫秒数。
 
方法摘要
-------------
 boolean after(date when)
          测试此日期是否在指定日期之后。
 
 boolean before(date when)
          测试此日期是否在指定日期之前。
 
 object clone()
          返回此对象的副本。
 
 int compareto(date anotherdate)
          比较两个日期的顺序。
 
 boolean equals(object obj)
          比较两个日期的相等性。
 
 long gettime()
          返回自 1970 年 1 月 1 日 00:00:00 gmt 以来此 date 对象表示的毫秒数。
 
 int hashcode()
          返回此对象的哈希码值。
 
 void settime(long time)
          设置此 date 对象,以表示 1970 年 1 月 1 日 00:00:00 gmt 以后 time 毫秒的时间点。
 
 string tostring()
          把此 date 对象转换为以下形式的 string: dow mon dd hh:mm:ss zzz yyyy 其中:
          dow 是一周中的某一天 (sun, mon, tue, wed, thu, fri, sat)。
          mon 是月份 (jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec)。
          dd 是一月中的某一天(01 至 31),显示为两位十进制数。
          hh 是一天中的小时(00 至 23),显示为两位十进制数。
          mm 是小时中的分钟(00 至 59),显示为两位十进制数。
          ss 是分钟中的秒数(00 至 61),显示为两位十进制数。
          zzz 是时区(并可以反映夏令时)。标准时区缩写包括方法 parse 识别的时区缩写。如果不提供时区信息,则 zzz 为空,即根本不包括任何字符。
          yyyy 是年份,显示为 4 位十进制数。

         下面是一个date类的综合实例:

public class testdate {
 public static void main(string[] args) {
  testdate testdate = new testdate();
  testdate.getsystemcurrenttime();
  testdate.getcurrentdate();
 }
 /**
  * 获取系统当前时间 
  * system.currenttimemillis()返回系统当前时间,结果为1970年1月1日0时0分0秒开始,到程序执行取得系统时间为止所经过的毫秒数 
  * 1秒=1000毫秒 
  */
 public void getsystemcurrenttime(){
  system.out.println("---获取系统当前时间---");
  system.out.println(system.currenttimemillis());
 }
 public void getcurrentdate(){
  system.out.println("---获取系统当前时间---");
   //创建并初始化一个日期(初始值为当前日期) 
  date date = new date(); 
  system.out.println("现在的日期是 = " + date.tostring()); 
  system.out.println("自1970年1月1日0时0分0秒开始至今所经历的毫秒数 = " + date.gettime()); 
 }
}

2、java.text.dateformat抽象类的使用
dateformat 是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并分析日期或时间。日期/时间格式化子类(如 simpledateformat)允许进行格式化(也就是日期 -> 文本)、分析(文本-> 日期)和标准化。将日期表示为 date 对象,或者表示为从 gmt(格林尼治标准时间)1970 年,1 月 1 日 00:00:00 这一刻开始的毫秒数。
dateformat 提供了很多类方法,以获得基于默认或给定语言环境和多种格式化风格的默认日期/时间 formatter。格式化风格包括 full、long、medium 和 short。方法描述中提供了使用这些风格的更多细节和示例。
dateformat 可帮助进行格式化并分析任何语言环境的日期。对于月、星期,甚至日历格式(阴历和阳历),其代码可完全与语言环境的约定无关。 
要格式化一个当前语言环境下的日期,可使用某个静态工厂方法:    

mystring = dateformat.getdateinstance().format(mydate);

 如果格式化多个日期,那么获得该格式并多次使用它是更为高效的做法,这样系统就不必多次获取有关环境语言和国家约定的信息了。

 dateformat df = dateformat.getdateinstance();
 for (int i = 0; i < mydate.length; ++i) {
 output.println(df.format(mydate[i]) + "; ");
 }

 
要格式化不同语言环境的日期,可在 getdateinstance() 的调用中指定它。
 dateformat df = dateformat.getdateinstance(dateformat.long, locale.france);
 还可使用 dateformat 进行分析。
 mydate = df.parse(mystring); 
使用 getdateinstance 来获得该国家的标准日期格式。另外还提供了一些其他静态工厂方法。使用 gettimeinstance 可获得该国家的时间格式。使用 getdatetimeinstance 可获得日期和时间格式。可以将不同选项传入这些工厂方法,以控制结果的长度(从 short 到 medium 到 long 再到 full)。确切的结果取决于语言环境,但是通常:
 short 完全为数字,如 12.13.52 或 3:30pm
 medium 较长,如 jan 12, 1952
 long 更长,如 january 12, 1952 或 3:30:32pm
 full 是完全指定,如 tuesday, april 12, 1952 ad 或 3:30:42pm pst。 
如果愿意,还可以在格式上设置时区。如果想对格式化或分析施加更多的控制(或者给予用户更多的控制),可以尝试将从工厂方法所获得的 dateformat 强制转换为 simpledateformat。这适用于大多数国家;只是要记住将其放入一个 try 代码块中,以防遇到特殊的格式。
 还可以使用借助 parseposition 和 fieldposition 的分析和格式化方法形式来:逐步地分析字符串的各部分。 对齐任意特定的字段,或者找出字符串在屏幕上的选择位置。 
dateformat 不是同步的。建议为每个线程创建独立的格式实例。如果多个线程同时访问一个格式,则它必须保持外部同步。 
3、java.text.simpledateformat(dateformat的直接子类)的使用 
simpledateformat 是一个以与语言环境相关的方式来格式化和分析日期的具体类。它允许进行格式化(日期 -> 文本)、分析(文本 -> 日期)和规范化。 
simpledateformat 使得可以选择任何用户定义的日期-时间格式的模式。但是,仍然建议通过 dateformat 中的 gettimeinstance、getdateinstance 或 getdatetimeinstance 来新的创建日期-时间格式化程序。每一个这样的类方法都能够返回一个以默认格式模式初始化的日期/时间格式化程序。可以根据需要使用 applypattern 方法来修改格式模式。有关使用这些方法的更多信息,请参阅 dateformat。

日期和时间模式
日期和时间格式由日期和时间模式 字符串指定。在日期和时间模式字符串中,未加引号的字母 'a' 到 'z' 和 'a' 到 'z' 被解释为模式字母,用来表示日期或时间字符串元素。文本可以使用单引号 (') 引起来,以免进行解释。"''" 表示单引号。所有其他字符均不解释;只是在格式化时将它们简单复制到输出字符串,或者在分析时与输入字符串进行匹配。
更多的参考信息可以查看jdk api文档,下面给出一个综合实例:

public class testdateformat {
 public static void main(string[] args) throws parseexception {
  testdateformat tdf = new testdateformat();
  tdf.dateformat();
 }
 /**
  * 对simpledateformat类进行测试
  * @throws parseexception 
  */
 public void dateformat() throws parseexception{
   //创建日期 
  date date = new date(); 

  //创建不同的日期格式 
  dateformat df1 = dateformat.getinstance(); 
  dateformat df2 = new simpledateformat("yyyy-mm-01 hh:mm:ss ee"); 
  dateformat df3 = dateformat.getdateinstance(dateformat.full, locale.china);  //产生一个指定国家指定长度的日期格式,长度不同,显示的日期完整性也不同 
  dateformat df4 = new simpledateformat("yyyy年mm月dd日 hh时mm分ss秒 ee", locale.china); 
  dateformat df5 = new simpledateformat("yyyy-mm-dd hh:mm:ss eeeeee", locale.us); 
  dateformat df6 = new simpledateformat("yyyy-mm-dd"); 

  //将日期按照不同格式进行输出 
  system.out.println("-------将日期按照不同格式进行输出------"); 
  system.out.println("按照java默认的日期格式,默认的区域      : " + df1.format(date)); 
  system.out.println("按照指定格式 yyyy-mm-dd hh:mm:ss ee ,系统默认区域  :" + df2.format(date)); 
  system.out.println("按照日期的full模式,区域设置为中文      : " + df3.format(date)); 
  system.out.println("按照指定格式 yyyy年mm月dd日 hh时mm分ss秒 ee ,区域为中文 : " + df4.format(date)); 
  system.out.println("按照指定格式 yyyy-mm-dd hh:mm:ss ee ,区域为美国  : " + df5.format(date)); 
  system.out.println("按照指定格式 yyyy-mm-dd ,系统默认区域     : " + df6.format(date)); 
  
  //将符合该格式的字符串转换为日期,若格式不相配,则会出错 
  date date1 = df1.parse("16-01-24 下午2:32"); 
  date date2 = df2.parse("2016-01-24 02:51:07 星期日"); 
  date date3 = df3.parse("2016年01月24日 星期五"); 
  date date4 = df4.parse("2016年01月24日 02时51分18秒 星期日"); 
  date date5 = df5.parse("2016-01-24 02:51:18 sunday"); 
  date date6 = df6.parse("2016-01-24"); 

  system.out.println("-------输出将字符串转换为日期的结果------"); 
  system.out.println(date1); 
  system.out.println(date2); 
  system.out.println(date3); 
  system.out.println(date4); 
  system.out.println(date5); 
  system.out.println(date6); 
 }
}

4、java.util.calendar(抽象类)
 java.util.calendar是个抽象类,是系统时间的抽象表示,它为特定瞬间与一组诸如 year、month、day_of_month、hour 等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。瞬间可用毫秒值来表示,它是距历元(即格林威治标准时间 1970 年 1 月 1 日的 00:00:00.000,格里高利历)的偏移量。
 与其他语言环境敏感类一样,calendar 提供了一个类方法 getinstance,以获得此类型的一个通用的对象。calendar 的 getinstance 方法返回一个 calendar 对象,其日历字段已由当前日期和时间初始化。
 一个calendar的实例是系统时间的抽象表示,从calendar的实例可以知道年月日星期月份时区等信息。calendar类中有一个静态方法get(int x),通过这个方法可以获取到相关实例的一些值(年月日星期月份等)信息。参数x是一个产量值,在calendar中有定义。 

calendar中些陷阱,很容易掉下去:
1、calendar的星期是从周日开始的,常量值为0。
2、calendar的月份是从一月开始的,常量值为0。
3、calendar的每个月的第一天值为1。 
5、java.util.gregoriancalendar(calendar的直接子类)
 
gregoriancalendar 是 calendar 的一个具体子类,提供了世界上大多数国家使用的标准日历系统。结合calendar抽象类使用。 
下面给出一个综合实例看看calendar类的用法:

public class testcalendar {
 public static void main(string[] args) throws parseexception {
  testcalendar testcalendar = new testcalendar();
  testcalendar.testcalendar();
  testcalendar.testcalendar2();
 }
 public void testcalendar(){
  //创建calendar的方式 
  calendar now1 = calendar.getinstance(); 
  calendar now2 = new gregoriancalendar(); 
  calendar now3 = new gregoriancalendar(2016, 01, 24); 
  calendar now4 = new gregoriancalendar(2016, 01, 24, 15, 55);  //陷阱:calendar的月份是0~11 
  calendar now5 = new gregoriancalendar(2016, 01, 24, 15, 55, 44); 
  calendar now6 = new gregoriancalendar(locale.us); 
  calendar now7 = new gregoriancalendar(timezone.gettimezone("gmt-8:00")); 

  //通过日期和毫秒数设置calendar 
  now2.settime(new date()); 
  system.out.println(now2); 

  now2.settimeinmillis(new date().gettime()); 
  system.out.println(now2); 


  //定义日期的中文输出格式,并输出日期 
  simpledateformat df = new simpledateformat("yyyy年mm月dd日 hh时mm分ss秒 e", locale.china); 
  system.out.println("获取日期中文格式化化输出:" + df.format(now5.gettime())); 
  system.out.println(); 

  system.out.println("--------通过calendar获取日期中年月日等相关信息--------"); 
  system.out.println("获取年:" + now5.get(calendar.year)); 
  system.out.println("获取月(月份是从0开始的):" + now5.get(calendar.month)); 
  system.out.println("获取日:" + now5.get(calendar.day_of_month)); 
  system.out.println("获取时:" + now5.get(calendar.hour)); 
  system.out.println("获取分:" + now5.get(calendar.minute)); 
  system.out.println("获取秒:" + now5.get(calendar.second)); 
  system.out.println("获取上午、下午:" + now5.get(calendar.am_pm)); 
  system.out.println("获取星期数值(星期是从周日开始的):" + now5.get(calendar.day_of_week)); 
  system.out.println(); 

  system.out.println("---------通用星期中文化转换---------"); 
  string dayofweek[] = {"", "日", "一", "二", "三", "四", "五", "六"}; 
  system.out.println("now5对象的星期是:" + dayofweek[now5.get(calendar.day_of_week)]); 
  system.out.println(); 

  system.out.println("---------通用月份中文化转换---------"); 
  string months[] = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"}; 
  system.out.println("now5对象的月份是: " + months[now5.get(calendar.month)]); 
 }
 
 public void testcalendar2() throws parseexception{
  //获取当前月份的最大天数
  calendar cal = calendar.getinstance(); 
  int maxday=cal.getactualmaximum(calendar.day_of_month); 
  int minday=cal.getactualminimum(calendar.day_of_month); 
  system.out.println(maxday);
  //取当月的最后一天 
  dateformat formatter3=new simpledateformat("yyyy-mm-"+maxday); 
  system.out.println(formatter3.format(cal.gettime()));
  //取当月的最后一天 
  dateformat formatter4=new simpledateformat("yyyy-mm-"+minday); 
  system.out.println(formatter4.format(cal.gettime()));
  //求两个日期之间相隔的天数
  java.text.simpledateformat format = new java.text.simpledateformat("yyyy-mm-dd"); 
  java.util.date begindate= format.parse("2007-12-24"); 
  java.util.date enddate= format.parse("2007-12-25"); 
  long day=(enddate.gettime()-begindate.gettime())/(24*60*60*1000); 
  system.out.println("相隔的天数="+day); 
  //一年前的日期
  java.text.format formatter5=new java.text.simpledateformat("yyyy-mm-dd"); 
  java.util.date todaydate=new java.util.date(); 
  long beforetime=(todaydate.gettime()/1000)-60*60*24*365; 
  todaydate.settime(beforetime*1000); 
  string beforedate=formatter5.format(todaydate); 
  system.out.println(beforedate); 
  calendar calendar = calendar.getinstance();
  calendar.add(calendar.year, -1);
  system.out.println(formatter5.format(calendar.gettime()));
  //当前星期的星期一和星期日
  simpledateformat dateformat = new simpledateformat("yyyymmdd");
  gregoriancalendar gregoriancalendar = new gregoriancalendar();
  int dayinweek = gregoriancalendar.get(calendar.day_of_week);
  int offset = 0;
  if (dayinweek == 1) {
   // 星期天
   offset = 6;
  } else {
   // 星期一至星期六
   offset = dayinweek - 2;
  }
  gregoriancalendar.add(gregoriancalendar.day_of_month, -offset);
  string sday = dateformat.format(gregoriancalendar.gettime());
  gregoriancalendar.add(gregoriancalendar.day_of_month, 6);
  string eday = dateformat.format(gregoriancalendar.gettime());

  system.out.println("这个星期的星期一:" + sday);
  system.out.println("这个星期的星期天:" + eday);
 }
 
}

三、总结

java中日期的经常有一下五个方面:
1、创建日期
2、日期格式化显示
3、日期的转换(主要是和字符串之间的相互转换)
4、日期中年、月、日、时、分、秒、星期、月份等获取。
5、日期的大小比较、日期的加减。

以上就是为大家总结的java日期时间使用方法,希望对大家的学习有所帮助。