提供了针对日期进行操作的诸多方法 提出使用Calendar类进行日期操作,日期的格式化交给DateFormat
第一个构造器是无参构造器,通过调用System的currentTimeMillis()方法来获取当前时间戳,这个时间戳是从1970年到当前时间的毫秒级数据
public Date() { this(System.currentTimeMillis()); }第二个构造器,可以将一个毫秒级的数据定义为Date格式的日期。
public Date(long date) { fastTime = date; }long getTime()方法:返回从1970年00:00:00到Date对象所代表时间的毫秒级数据
public long getTime() { return getTimeImpl(); }void setTime(long time)方法:设置一个Date对象用来代表从1970年00:00:00开始的一段毫秒级数据后所代表的时间点
public void setTime(long time) { fastTime = time; cdate = null; }boolean before(Date when)方法:判断Date对象所代表的时间点是否在when所代表的时间点之前
public boolean before(Date when) { return getMillisOf(this) < getMillisOf(when); }boolean after(Date when)方法:判断Date对象所代表的时间点是否在when所代表的时间点之后
public boolean after(Date when) { return getMillisOf(this) > getMillisOf(when); }例子:
/** * 计算某代码的性能 */ //一层循环 private void circle1(){ for (int i =0;i<100000;i++ ){ System.out.println(i); } } @Test public void test5() { long star=System.currentTimeMillis(); circle1(); long end=System.currentTimeMillis(); System.out.println(end-star); }例子:
@Test public void test6() { Date d=new Date(); SimpleDateFormat df=new SimpleDateFormat("yyyy年MM月dd日hh时:mm分:ss秒ms毫秒"); //把日期时间格式化成字符串 String cur=df.format(d); System.out.println(cur); try { //把符合模式串的字符转换成Date对象 Date dd=df.parse("2019年05月19日21时:04分:13秒05毫秒"); }catch(ParseException e){ e.printStackTrace(); } }该类被abstract所修饰,说明不能通过new的方式来获得实例,对此,Calendar提供了一个类方法getInstance,以获得此类型的一个通用的对象,getInstance方法返回一个Calendar对象(该对象为Calendar的子类对象),其日历字段已由当前日期和时间初始化:
Calendar rightNow = Calendar.getInstance();通过测试类进行下列代码理解:注意每个国家地区都有自己的一套日历算法,比如西方国家的第一个星期大部分为星期日
import org.junit.Before; import org.junit.Test; import java.util.Calendar; public class Test2 { private Calendar calendar=null; @Before //在所有的测试方法之前执行 public void test1(){ calendar=Calendar.getInstance();//对子类进行实例化 } /** * 从日历中获得当前时间 */ @Test public void test2(){ System.out.println(calendar.getTime()); } /** * 日历类的基本用法 */ @Test public void test3(){ //取年 int year=calendar.get(Calendar.YEAR); //取月 int month=calendar.get(Calendar.MONDAY); //取日 int day=calendar.get(Calendar.DAY_OF_MONTH); //取时 int hour=calendar.get(Calendar.HOUR); //取分 int minute=calendar.get(Calendar.MINUTE); //取秒、 int second=calendar.get(Calendar.SECOND); //取星期几 int weekday=calendar.get(Calendar.DAY_OF_WEEK); System.out.println(year+"年"+month+"月"+day+"日"+hour+"时"+minute+"分"+second+"秒"); } @Test public void test4(){ //当前时间增加一年 //amount 正值是增加几年 负值时减少几年 calendar.add(Calendar.YEAR,-13); //取年 int year=calendar.get(Calendar.YEAR); //取月 int month=calendar.get(Calendar.MONDAY); //取日 int day=calendar.get(Calendar.DAY_OF_MONTH); System.out.println(year+"年"+month+"月"+day+"日"); } /** * 2014年2月最后一天时星期几 */ @Test public void test5(){ calendar.set(2014,2,1); calendar.add(Calendar.DAY_OF_MONTH,-1); int day=calendar.get(Calendar.DAY_OF_WEEK); System.out.println(day); } }