package util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Test {
public static void main(String[] args) throws ParseException {
// 获取当前年份、月份、日期
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DATE);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int dom = cal.get(Calendar.DAY_OF_MONTH);
int dow = cal.get(Calendar.DAY_OF_WEEK);
System.out.println("当前时间: " + cal.getTime());
System.out.println("年: " + year);
System.out.println("月: " + month);
System.out.println("日: " + day);
System.out.println("小时: " + hour);
System.out.println("分钟: " + minute);
System.out.println("秒: " + second);
System.out.println("Day of Month: " + dom);
System.out.println("Day of Week: " + dow);
// 获取当月第一天和最后一天
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String firstday, lastday,lastMonthFirstDay,lastMonthLastDay;
// 获取第一天
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
firstday = sdf.format(cal.getTime());
// 获取最后一天
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 0);
lastday = sdf.format(cal.getTime());
System.out.println("本月第一天和最后一天分别是 : " + firstday + " ---- " + lastday);
// 获取上个月第一天
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH, 1);
lastMonthFirstDay = sdf.format(cal.getTime());
// 获取上个月最后一天
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 0);
lastMonthLastDay = sdf.format(cal.getTime());
System.out.println("上个月第一天和最后一天分别是 : " + lastMonthFirstDay + " ---- " + lastMonthLastDay);
}
}
使用Calendar获取当前年份 月份,当月第一天和最后一天,上个月第一天和最后一天
最新推荐文章于 2024-07-15 10:01:29 发布