java 获取当前年份 月份,当月第一天和最后一天
获取当前年份 月份,当月第一天和最后一天,工作中会经常用到,下面是代码:
package basic.day01;import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
// 获取当前年份、月份、日期
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 dow = cal.get(Calendar.DAY_OF_WEEK);
int dom = cal.get(Calendar.DAY_OF_MONTH);
int doy = cal.get(Calendar.DAY_OF_YEAR);
System.out.println("Current Date: " + cal.getTime());
System.out.println("Year: " + year);
System.out.println("Month: " + month);
System.out.println("Day: " + day);
System.out.println("Hour: " + hour);
System.out.println("Minute: " + minute);
System.out.println("Second: " + second);
System.out.println("Day of Week: " + dow);
System.out.println("Day of Month: " + dom);
System.out.println("Day of Year: " + doy);
//当前季度 (当前月转换季度)
String quarter = "";
int m = cal.get(Calendar.MONTH) + 1;
if (m >= 1 && m <= 3) {
quarter = "1";
} else if (m >= 4 && m <= 6) {
quarter = "2";
} else if (m >= 7 && m <= 9) {
quarter = "3";
} else {
quarter = "4";
}
System.out.println("Quarter: " + quarter);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd HH:mm");
SimpleDateFormat format3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 获取当前日期字符串
Date d = new Date();
System.out.println("当前日期字符串1:" + format1.format(d));
System.out.println("当前日期字符串2:" + format2.format(d));
System.out.println("当前日期字符串3:" + format3.format(d));
//拼装日期字符串
System.out.println("当前日期字符串4:" + year + "/" + month + "/" + day + " "
+ hour + ":" + minute + ":" + second);
}
}
good luck!
以上是 java 获取当前年份 月份,当月第一天和最后一天 的全部内容, 来源链接: utcz.com/z/392187.html