获取年月日时分秒
Calendar cal = Calendar.getInstance();
//获取年
int year = cal.get(Calendar.YEAR);
//获取月,范围是0-11,最后使用需+1
int month = cal.get(Calendar.MONTH);
//获取日
int day = cal.get(Calendar.DAY_OF_MONTH);
//获取小时
int hour = cal.get(Calendar.HOUR_OF_DAY);
//获取分钟
int minute = cal.get(Calendar.MINUTE);
//获取秒
int second = cal.get(Calendar.SECOND);
在Java 8中可以用如下方法获取年月日时分秒
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt.getYear());
//获取月份,范围 1-12
System.out.println(ldt.getMonthValue());
System.out.println(ldt.getDayOfMonth());
System.out.println(ldt.getHour());
System.out.println(ldt.getMinute());
System.out.println(ldt.getSecond());
取得从1970年1月1日0时0分0秒到现在的毫秒数
long timeInMillis = Calendar.getInstance().getTimeInMillis();
如何取得某月的最后一天?
static String getLastDayOfMonth(int year,int month) {
Calendar cal = Calendar.getInstance();
//获取年
cal.set(Calendar.YEAR, year);
//获取月份
cal.set(Calendar.MONTH, month-1);
//获取某月的最大天数
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
//设置日历中月份最大天数
cal.set(Calendar.DAY_OF_MONTH, lastDay);
//格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String lastDayOfMonth = sdf.format(cal.getTime());
return lastDayOfMonth;
}
public static void main(String[] args) {
String lastDayOfMonth = getLastDayOfMonth(2018, 10);
System.out.println(lastDayOfMonth);
}
打印昨天的当前时刻
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(cal.getTime());
在Java 8 中用如下代码也可实现
LocalDateTime today = LocalDateTime.now();
LocalDateTime yesterday = today.minusDays(1);
System.out.println(yesterday);