时间的重要性
时间就是生命,时间的处理的重要性是不言而喻的。基本上每一种编程语言中,时间处理都是必不可少的,但要记住这些处理时间的方式,也是比较繁琐的,唯一的途径就是多写多练。
主要的时间处理类
- java.util.Date
- java.util.Calendar
- java.util.GregorianCalendar
- java.text.DateFormat
操作时间:获取和设置时间
java.util.Date
中的很多方法都已经被标记为过时,相对来说它已经没有那么重要。基本上Date类中的功能现在都已经迁移到了java.util.Calendar
类。现在的Date类基本上变成了其他类的辅助类。
初始化一个Date对象
目前未被废弃的Date对象的构造函数只有一个:带一个long类型参数的构造函数
1 2 3 4 5 6 7 8 9 10 11 |
public static void main(String[] args){ Date date = new Date(System.currentTimeMillis()); System.out.println(date); /** * Fri Mar 03 00:02:51 CST 2017 */ } |
输出内容如上面的注释。但是很多时候我们都不需要这么多东西,使用SimpleDateFormat
类可以把时间格式简化。
使用SimpleDateFormat
SimpleDateFormat类在java.text
包中,继承自DateFormat
抽象类,其作用是格式化时间格式。用户可以通过向构造函数传入一个自定义的字符串格式来获取指定的输出。
1 2 3 4 5 6 7 8 9 10 11 12 |
public static void main(String[] args){ Date date = new Date(System.currentTimeMillis()); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formatedDate = dateFormat.format(date); System.out.println(formatedDate); /** * 2017-03-03 00:33:02 */ } |
时间比较
我们可以比较两个Date对象的实例是否相同,因为Date类实现了java.lang.Comparable
接口。话已经说到这里,想必大家应该也想到了compareTo()
方法。下面是两个Date对象实例的简单比较:
1 2 3 4 5 6 7 8 9 10 11 12 |
public static void main(String[] args){ Date date1 = new Date(System.currentTimeMillis()); Date date2 = new Date(System.currentTimeMillis()); int result = date1.compareTo(date2); System.out.println(result); /** * 输出结果 0 * */ } |
输出结果为0。根据compareTo()的返回规则
,我们应该猜测这两个实例是相等的。通常compareTo的返回规则如下
- 如果返回结果等于0,说明两个对象相等
- 如果返回结果小于0,说明调用compareTo方法的对象小于作为compareTo参数的对象
- 如果返回结果大于0,说明调用compareTo方法的对象大于作为compareTo参数的对象
用一个简单的例子说明一下:
1 2 3 4 5 6 |
public static void main(String[] args){ Integer ten = new Integer(10); Integer twenty = new Integer(20); int res = ten.compareTo(twenty); System.out.println(res); } |
上面这段代码的返回结果是-1,很明显,10肯定比20要小。如果twenty.compareTo(ten)
,那么,返回结果就是1,即20>10
。回过头来说时间的比较,前一段代码中我们是先后创建两个Date对象的,它们的创建时间应该有所区别才对!但是不要忘记,System.currentTimeMillis()
并不确保时间的精确性,况且,两个Date对象的创建时间差是微乎其微的,基本可以忽略,因此它们相等也不足为奇。
再看多一个例子,我们先创建一个Date对象,然后让线程睡眠3秒钟
,接着创建第二个Date对象。最后比较这两个对象的大小:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public static void main(String[] args){ Date date1 = new Date(System.currentTimeMillis()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } Date date2 = new Date(System.currentTimeMillis()); int result = date2.compareTo(date1); System.out.println(result); /** * 输出结果为1,说明date2对象比date1对象的时间要迟 */ } |
除了compareTo方法外,java.util.Date下还有其他比较时间的方法,它们分别是before()
和after()
方法。下面是简单的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public static void main(String[] args){ Date date1 = new Date(System.currentTimeMillis()); try{ Thread.sleep(2000); }catch(InterruptedException e){ e.printStackTrace(); } Date date2 = new Date(System.currentTimeMillis()); boolean isBefore = date1.before(date2); boolean isAfter = date1.after(date2); System.out.println(isBefore); System.out.println(isAfter); /** * 输出结果为true false */ } |
转载请注明:Pure nonsense » java每日一练之时间处理(一)使用Date