在日常编码中经常需要使用到当前时间以及本月初等相关时间数据,很多时候获取当前时间都用new Date()方式,用起来极为不方便。下面是通过Calendar类来获取当前时间的方法:
Date date = Calendar.getInstance().getTime();
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
String today = simpleFormat.format(date);
其中Calendar.getInstance()方法会创建当前时间的实例(类为Calendar)。通过调用getTime()方法,获取当前时间的date类型
SimpleDateFormat 时间格式的设置,通过在new对象时设置不同的格式,我这里使用的格式为yyyy-MM-dd,如果要使用其他的格式,则在创建实例时,设置不同的格式。
通过调用formate(Date date) 方法,会将参数的时间转化为目标时间格式。
我的输出结果为:2014-10-14
同时,Calendar类也能够获取一些时间相关的信息,如:本月第一天、本月最后一天等等。
本月第一天:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH,1);
Date date = calendar.getTime();
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(simpleFormat.format(date));
本月最后一天:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH,1);
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date date = calendar.getTime();
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(simpleFormat.format(date));