Date相关

java.lang.Object
   |--java.util.Date
      |--java.sql.Date
      |--java.sql.Timestamp

java.lang.Object
   |--java.text.Format
      |--java.text.DateFormat (抽象类, 不能通过构造函数构造对象, 只可以通过getDateTimeInstance()方法获得该对象)
         |--java.text.SimpleDateFormat (具体类)

java.lang.Object
   |--java.util.Calendar (抽象类)
      |--java.util.GregorianCalendar (具体类)

1.Date

(1)介绍:实际上只是一个包裹类, 它包含的是一个长整型数据, 表示的是从GMT(格林尼治标准时间)1970年, 1月1日00:00:00这一刻之前或者是之后经历的毫秒数. Date类从JDK 1.0就开始进化, 当时它只包含了几个取得或者设置一个日期数据的各个部分的方法, 比如说月, 日, 和年. 这些方法现在遭到了批评并且已经被转移到了Calendar类里去了, 这种改进旨在更好的处理日期数据的国际化格式.

(2)Date最常用的两个方法:java.sql.Date和java.util.Date中的很多方法都已经Deprecated了,不能再用。除了getTime()和setTime()方法。这里要注意与Calendar类的getTime()和setTime()方法的区别。

public long getTime() --> Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

public void setTime(long time) --> Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

2.SimpleDateFormat:用来格式化日期

(1)将Date转换为String (format()方法)

  1. package edu.hust.test;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. import java.util.Locale ;
  5. public class DateExample01 {
  6.     public static void main(String[] args) {
  7.         //我们使用Date构造函数创建一个日期对象, 这个构造函数没有接受任何参数. 而这个构造函数在内部使用了System.currentTimeMillis()方法来从系统获取日期, 表示使用系统的当前日期和时间创建一个日期对象. 
  8.         Date date = new Date(); 
  9.         
  10.         //返回一个long型数据:表示从1970年1月1日开始 至目前程序执行这个时刻 所经历的毫秒数.
  11.         long lDate = date.getTime(); 
  12.         System.out.println("当前时间为:" + lDate);
  13.         
  14.         //通过"构造方法"定义日期输出格式, 第二个参数用来 设置时区
  15.         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy, EEEE", Locale.ENGLISH);
  16.         String strDate = simpleDateFormat.format(date);
  17.         System.out.println("用/"MM-dd-yyyy, EEEE/"格式输出当前时间:" + strDate);
  18.         
  19.         //通过"applyPattern()"定义日期输出格式
  20.         simpleDateFormat.applyPattern("yyyy年MM月dd日, HH时mm分ss秒");
  21.         strDate = simpleDateFormat.format(date);
  22.         System.out.println("applyPattern()方法改变时间输出格式:" + strDate);
  23.         
  24.         /*
  25.          * 参看帮助文档:获得日期格式化选项的完整指示
  26.          * 
  27.          * 结果为:
  28.          * 当前时间为:1221968674984
  29.          * 用"MM-dd-yyyy, EEEE"格式输出当前时间:09-21-2008, Sunday
  30.          * applyPattern()方法改变时间输出格式:2008年09月21日, 11时44分34秒
  31.          * */
  32.     }
  33.     
  34. }

(2)将String(前提:这个String对象必须是日期格式)转换为Date(即将String: 08-08-2008 转换为 long:1199721600000) (parse()方法)

  1. package edu.hust.test;
  2. import java.text.ParseException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import java.util.Locale;
  6. public class DateExample02 {
  7.     public static void main(String[] args) {
  8.         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-DD-yyyy", Locale.CHINESE);
  9.         String strDate = "08-08-2008";
  10.         
  11.         Date date = null;
  12.         try {
  13.             date = simpleDateFormat.parse(strDate);
  14.         } catch (ParseException e) {
  15.             System.out.println("您的日期格式输入有错误, 请按/"MM-DD-yyyy/"格式输入");
  16.         }
  17.         
  18.         long lDate = date.getTime();
  19.         
  20.         System.out.println("将输入日期转换为long型数据, /"08-08-2008/"对应long型数据为:" + lDate);
  21.         
  22.     }
  23. }

(3)使用DateFormat格式化日期(不常用)

DateFormat可通过getDateTimeInstance()方法获得其对象,DateFormat参数是final常量,系统根据这些常量输出当前时间。注意我们在对getDateTimeInstance的每次调用中都传递了两个值. 第一个参数是日期风格, 而第二个参数是时间风格. 它们都是基本数据类型int(整型). 考虑到可读性, 我们使用了DateFormat类提供的常量: SHORT, MEDIUM, LONG, 和 FULL.

  1. package edu.hust.test;
  2. import java.text.DateFormat; 
  3. import java.util.Date; 
  4. public class DateExample02 {
  5.     public static void main(String[] args) { 
  6.         Date date = new Date();  
  7.         DateFormat shortDateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);         
  8.         DateFormat mediumDateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);         
  9.         DateFormat longDateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);         
  10.         DateFormat fullDateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);         
  11.         System.out.println(shortDateFormat.format(date));         
  12.         System.out.println(mediumDateFormat.format(date));         
  13.         System.out.println(longDateFormat.format(date));         
  14.         System.out.println(fullDateFormat.format(date));     
  15.     }
  16. }

3.GregorianCalendar:用来设置时间, 可以单独设置yyyy或MM或dd或HH或mm或ss, 或者其任意组合;用来时间的计算.

(1)时间的设置. 注意与Date类的getTime()和setTime()方法的区别。

public final void setTime(Date date) --> Sets this Calendar's time with the given Date.

public final Date getTime() --> Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

public void set(int field, int value) --> Sets the given calendar field with the given value.

public int get(int field) --> Returns the value of the given calendar field

public abstract void add(int field, int amount) --> Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling: add(Calendar.DAY_OF_MONTH, -5).

  1. package edu.hust.test;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Calendar;
  4. import java.util.Date;
  5. import java.util.GregorianCalendar;
  6. import java.util.Locale;
  7. public class DateExample03 {
  8.     public static void main(String[] args) {
  9.         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy, EEEE, HH点mm分ss秒", Locale.CHINESE);
  10.         
  11.         GregorianCalendar gregorianCalendar = new GregorianCalendar();
  12.         gregorianCalendar.setTime(new Date());
  13.         
  14.         String strDate = simpleDateFormat.format(gregorianCalendar.getTime());
  15.         
  16.         System.out.println("当前时间为:" + strDate);
  17.         
  18.         //利用set()将gregorianCalendar的日期 定位到 当前星期的FRIDAY,此时gregorianCalendar中存储的时间就是本周星期五的 程序运行的时刻.
  19.         gregorianCalendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
  20.         
  21.         strDate = simpleDateFormat.format(gregorianCalendar.getTime());
  22.         System.out.println("本周星期五的时间为:" + strDate);
  23.         
  24.         int i = 0;
  25.         //产生10个星期五与13日重叠的日期.
  26.         while (i < 10) {
  27.             //利用add()将gregorianCalendar的日期 定位到 7天以后, 即下个星期的星期五.
  28.             gregorianCalendar.add(Calendar.DAY_OF_MONTH, 7);
  29.             if (gregorianCalendar.get(Calendar.DAY_OF_MONTH) == 13) {
  30.                 strDate = simpleDateFormat.format(gregorianCalendar.getTime());
  31.                 System.out.println("从当前时刻起, 星期五与13日重叠的日期有:" + strDate);
  32.                 i++;
  33.             }
  34.             
  35.         }
  36.         
  37.         /*
  38.          * 当前时间为:09-21-2008, 星期日, 11点16分16秒
  39.          * 
  40.          * 本周星期五的时间为:09-26-2008, 星期五, 11点16分16秒
  41.          * 
  42.          * 从当前时刻起, 星期五与13日重叠的日期有:02-13-2009, 星期五, 11点16分16秒
  43.          * 从当前时刻起, 星期五与13日重叠的日期有:03-13-2009, 星期五, 11点16分16秒
  44.          * 从当前时刻起, 星期五与13日重叠的日期有:11-13-2009, 星期五, 11点16分16秒
  45.          * 从当前时刻起, 星期五与13日重叠的日期有:08-13-2010, 星期五, 11点16分16秒
  46.          * 从当前时刻起, 星期五与13日重叠的日期有:05-13-2011, 星期五, 11点16分16秒
  47.          * 从当前时刻起, 星期五与13日重叠的日期有:01-13-2012, 星期五, 11点16分16秒
  48.          * 从当前时刻起, 星期五与13日重叠的日期有:04-13-2012, 星期五, 11点16分16秒
  49.          * 从当前时刻起, 星期五与13日重叠的日期有:07-13-2012, 星期五, 11点16分16秒
  50.          * 从当前时刻起, 星期五与13日重叠的日期有:09-13-2013, 星期五, 11点16分16秒
  51.          * 从当前时刻起, 星期五与13日重叠的日期有:12-13-2013, 星期五, 11点16分16秒
  52.          * 
  53.          * */
  54.         
  55.     }
  56. }

(2)时间的计算:计算出两个时间之间相差几小时、几分钟、几秒钟,怎么做?

方法1

  1. package edu.hust.test;
  2. import java.util.GregorianCalendar;
  3. public class DateExample04 {
  4.     public static void main(String[] args) {        
  5.         GregorianCalendar gregorianCalendar_Start = new GregorianCalendar();
  6.         GregorianCalendar gregorianCalendar_End = new GregorianCalendar();
  7.         
  8.         gregorianCalendar_Start.set(20088-182088); //2008年8月8日, 晚8点8分8秒. 注意:Calendar的月份是从0开始计数的.
  9.         gregorianCalendar_End.set(20088-192080); //2008年8月9日, 晚8点8分0秒.
  10.         
  11.         //获得两个时间点的时间差, 单位是毫秒(ms), 这个时间差是long型数据.
  12.         //gregorianCalendar_End.getTime().getTime() 等效于 gregorianCalendar_End.getTimeInMillis()
  13.         long difference = gregorianCalendar_End.getTime().getTime() - gregorianCalendar_Start.getTime().getTime();
  14.         
  15.         //获得两个时间点的时间差, 单位是时/分/秒(h/mm/ss).
  16.         int difference_Hour = (int) difference/1000/60/60;
  17.         int difference_Minute = (int) difference/1000/60 - difference_Hour * 60;
  18.         int difference_Second = (int) difference/1000 - (difference_Hour * 60 * 60 + difference_Minute * 60);
  19.         
  20.         System.out.println("两个时间点的时间差为:" + difference_Hour + "(小时)" + difference_Minute + "(分钟)" + difference_Second + "(秒)");
  21.     }
  22.     /*
  23.      * 输出结果:两个时间点的时间差为:23(小时)59(分钟)52(秒)
  24.      * */
  25. }

方法2

  1. package edu.hust.test;
  2. import java.util.Calendar;
  3. import java.util.GregorianCalendar;
  4. public class DateExample05 {
  5.     /*
  6.      * public final void set(int year, int month, int date, int hourOfDay, int minute, int second)
  7.      * Sets the values for the fields YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE, and SECOND. Previous values of other fields are retained. If this is not desired, call clear() first. 
  8.      * Parameters:
  9.      *   year - the value used to set the YEAR calendar field.
  10.      *   month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
  11.      *   date - the value used to set the DAY_OF_MONTH calendar field.
  12.      *   hourOfDay - the value used to set the HOUR_OF_DAY calendar field.
  13.      *   minute - the value used to set the MINUTE calendar field.
  14.      *   second - the value used to set the SECOND calendar field.
  15.      * 
  16.      * */
  17.     public static void main(String[] args) {
  18.         /*
  19.          * Calendar.HOUR            :12小时制
  20.          * Calendar.HOUR_OF_DAY     :24小时制
  21.          * 
  22.          * Calendar.DAY_OF_MONTH    :指定日期位于所在月中 第几天
  23.          * Calendar.DAY_OF_WEEK     :指定日期位于所在星期中 第几天
  24.          * Calendar.DAY_OF_YEAR     :指定日期位于所在年中 第几天
  25.          * 
  26.          * */
  27.         GregorianCalendar gregorianCalendar_Start = new GregorianCalendar();
  28.         GregorianCalendar gregorianCalendar_End = new GregorianCalendar();
  29.         
  30.         gregorianCalendar_Start.set(20088-182088); //2008年8月8日, 晚8点8分8秒. 注意:Calendar的月份是从0开始计数的.
  31.         gregorianCalendar_End.set(20098-192200); //2009年8月9日, 晚10点0分0秒.
  32.         
  33.         int difference_Year = gregorianCalendar_End.get(Calendar.YEAR) - gregorianCalendar_Start.get(Calendar.YEAR);
  34.         int difference_Month = gregorianCalendar_End.get(Calendar.MONTH) - gregorianCalendar_Start.get(Calendar.MONTH);
  35.         int difference_Date = gregorianCalendar_End.get(Calendar.DAY_OF_MONTH) - gregorianCalendar_Start.get(Calendar.DAY_OF_MONTH);
  36.         int difference_Hour = gregorianCalendar_End.get(Calendar.HOUR_OF_DAY) - gregorianCalendar_Start.get(Calendar.HOUR_OF_DAY);
  37.         int difference_Minute = gregorianCalendar_End.get(Calendar.MINUTE) - gregorianCalendar_Start.get(Calendar.MINUTE);
  38.         int difference_Second = gregorianCalendar_End.get(Calendar.SECOND) - gregorianCalendar_Start.get(Calendar.SECOND);
  39.         
  40.         System.out.println("两个时间点的'年'差为:" + difference_Year);
  41.         System.out.println("两个时间点的'月'差为:" + difference_Month);
  42.         System.out.println("两个时间点的'日'差为:" + difference_Date);
  43.         System.out.println("两个时间点的'时'差为:" + difference_Hour);
  44.         System.out.println("两个时间点的'分'差为:" + difference_Minute);
  45.         System.out.println("两个时间点的'秒'差为:" + difference_Second);
  46.         
  47.         System.out.println(getIntervalDays(gregorianCalendar_Start, gregorianCalendar_End));
  48.     }
  49. }

(3)天数差的计算, 把这个单独拿出来是因为应用很广泛.

  1. package edu.hust.test;
  2. import java.util.Calendar;
  3. import java.util.GregorianCalendar;
  4. public class DateExample05 {
  5.     
  6.     public static void main(String[] args) {
  7.         
  8.         GregorianCalendar gregorianCalendar_Start = new GregorianCalendar();
  9.         GregorianCalendar gregorianCalendar_End = new GregorianCalendar();
  10.         
  11.         gregorianCalendar_Start.set(20088-182088); //2008年8月8日, 晚8点8分8秒. 注意:Calendar的月份是从0开始计数的.
  12.         gregorianCalendar_End.set(20098-192200); //2009年8月9日, 晚10点0分0秒.
  13.         
  14.         System.out.println(getIntervalDays(gregorianCalendar_Start, gregorianCalendar_End));
  15.     }
  16.     
  17.     public static int getIntervalDays(Calendar calendar_Start, Calendar calendar_End) {
  18.         if (calendar_Start.after(calendar_End)) {
  19.             Calendar temp;
  20.             temp = calendar_Start;
  21.             calendar_Start = calendar_End;
  22.             calendar_End = temp;
  23.         }
  24.         int difference_Day = calendar_End.get(Calendar.DAY_OF_YEAR) - calendar_Start.get(Calendar.DAY_OF_YEAR);
  25.         if (calendar_End.get(Calendar.YEAR) != calendar_Start.get(Calendar.YEAR)) {
  26.             while (calendar_End.get(Calendar.YEAR) != calendar_Start.get(Calendar.YEAR)) {
  27.                 difference_Day += calendar_Start.getActualMaximum(Calendar.DAY_OF_YEAR);
  28.                 calendar_Start.add(Calendar.YEAR, 1);
  29.             }
  30.         }
  31.         return difference_Day;
  32.     }
  33.     /*
  34.      * 应用:如要查出邮箱三周之内收到的邮件(得到当前系统时间, 再得到三周前时间)用收件的时间去匹配, 而且最好装化成long去比较, 这样更为精确.
  35.      * 
  36.      * */
  37. }

4.java.sql.Date与java.util.Date

在开发web应用中,针对不同的数据库日期类型,我们需要在我们的程序中对日期类型做各种不同的转换。若对应数据库数据是oracle的Date类型,即只需要年月日的,可以选择使用java.sql.Date类型,若对应的是MSsqlserver 数据库的DateTime类型,即需要年月日时分秒的,选择java.sql.Timestamp类型

(1).java.util.Date与java.sql.Date的相互转换

先讲解一下public int getActualMaximum(int field)方法怎么用.

  1. package edu.hust.test;
  2. import java.util.Calendar;
  3. import java.util.GregorianCalendar;
  4. public class DateExample06 {
  5.     public static void main(String[] args) {
  6.         GregorianCalendar gregorianCalendar = new GregorianCalendar();
  7.         gregorianCalendar.clear(); //在使用set方法之前,必须先clear一下,否则很多信息会继承自系统当前时间
  8.         
  9.         gregorianCalendar.set(Calendar.YEAR, 2008);
  10.         gregorianCalendar.set(Calendar.MONTH, 2-1); //注意,Calendar对象默认一月为0
  11.         
  12.         int week_Days = gregorianCalendar.getActualMaximum(Calendar.DAY_OF_WEEK); //获得当前日期所在周的总天数
  13.         int month_Days = gregorianCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); //获得当前日期所在月的总天数
  14.         int year_Days = gregorianCalendar.getActualMaximum(Calendar.DAY_OF_YEAR); //获得当前日期所在年的总天数
  15.         
  16.         
  17.         System.out.println("当前日期所在周的总天数为:" + week_Days);
  18.         System.out.println("当前日期所在月的总天数为:" + month_Days);
  19.         System.out.println("当前日期所在年的总天数为:" + year_Days);
  20.     }
  21. }

java.sql.Date和java.util.Date的转换

  1. package edu.hust.test;
  2. public class DateExample07 {
  3.     public static void main(String[] args) {
  4.         java.sql.Date sqlDate;
  5.         java.util.Date utilDate;
  6.         
  7.         utilDate = new java.util.Date();
  8.         System.out.println("初始定义utilDate:" + utilDate);
  9.         
  10.         sqlDate = new java.sql.Date(utilDate.getTime());
  11.         System.out.println("转型sqlDate:" + sqlDate);
  12.         
  13.         utilDate = (java.util.Date) sqlDate;
  14.         System.out.println("转型utilDate:" + utilDate);
  15.     }
  16.     /*
  17.      * 输出结果:
  18.      * 初始定义utilDate:Sun Sep 21 16:22:38 CST 2008
  19.      * 转型sqlDate:2008-09-21
  20.      * 转型utilDate:2008-09-21
  21.      * 
  22.      * */
  23. }

(2)java.sql.Date的值 存入/取出 DB中Date字段中会发生数据截取,为什么?

java.sql.Date是为了配合SQL Date而设置的数据类型。"规范化"的java.sql.Date只包含年月日信息,时分秒毫秒都会清零,格式类似:YYYY-MM-DD。

当我们把一个java.sql.Date值通过PrepareStatement的setDate方法存入数据库时,java程序会对传入的java.sql.Date规范化,非规范化的部分将会被劫取;当我们调用ResultSet的getDate()方法来获得返回值时,java程序会参照"规范"的java.sql.Date来格式化数据库中的数值,非规范化部分将会被劫取。

注:PreparedStament的setDate()的第2参数和ResultSet的getDate()方法的第2个参数都是java.sql.Date

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值