说到Java的日期,要提到一个小故事。公元前和公元后日期符号分别为BC和AD这里的BC为Before Christ而AD表示Anno Domini(希腊语:有上帝的年)。现在一般采用的BCE和CE来表示。Java早期版本时间起始为1970-1-1日,后期加入许多其它日历类,我们来模拟一个现实时间的程序:
Date date = newDate(); System.out.println(date); DateFormat df =DateFormat.getDateInstance(); System.out.println(df.format(date)); DateFormat df2 =DateFormat.getDateInstance(DateFormat.FULL, Locale.CHINA); System.out.println(df2.format(date)); SimpleDateFormatsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(sdf.format(date)); Calendar c =Calendar.getInstance(); c.set(2013, 0,1); System.out.println(DateFormat.getDateInstance(DateFormat.LONG).format(c.getTime()));
字符串转换为日期使用的是DateFormat的parse方法。
StringdateString = args[0]!=null?args[0]:"2012-12-12"; SimpleDateFormatsdf2 = new SimpleDateFormat("yyyy-MM-dd"); Date d =sdf2.parse(dateString);
对于日期的加减可以使用Date的getTime方法得到毫秒,在此基础上进行加减毫秒的运算。也可以使用Calendar的add方法加减一定时间。实例如下:
Date d =sdf2.parse(dateString); System.out.println(sdf2.format(d)); Date now = newDate(); long t =now.getTime(); t -=2*24*60*60*1000; Date then = newDate(t); System.out.println(sdf2.format(then)); Calendar c =Calendar.getInstance(); System.out.println(sdf2.format(c.getTime())); c.add(Calendar.YEAR,1); System.out.println(sdf2.format(c.getTime()));
对于两个日期之间的间隔,求法为将两个时间转换为长整型,再相减,最后将差值进行格式化:
long a =sdf2.parse("1987-02-16").getTime(); long b = newDate().getTime(); long distance =b-a; System.out.println(distance);
比较日期采用转化为long型毫秒值的方式,大值为在后的日期信息,小值为在前的日期。同时Date对象有equals方法。提供了before和after方法。同时system的两个方法nanoTime返回当前系统时间的毫微秒,currentTimeMillis返回当前系统的毫秒时间。
long start =System.nanoTime(); long startms =System.currentTimeMillis(); a =sdf2.parse("1987-02-16"); Date b =sdf2.parse("1987-02-15"); System.out.println(a.equals(b)); System.out.println(a.before(b)); System.out.println(a.after(b)); Calendar c =Calendar.getInstance(); System.out.println(c.get(Calendar.DAY_OF_MONTH)); System.out.println((System.nanoTime()-start)/1000+"ns"); System.out.println(System.currentTimeMillis()-startms+"ms");