Java中获取上个月的第一天和最后一天可能用于某些统计数据操作。
package com.yxjc;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Test {
public static void main(String args[]) throws ParseException {
//获取上个月的第一天
System.out.println(Test.getLastMonthFirstDay("yyyy-MM-dd HH:mm:ss"));
//获取上个月的最后一天
System.out.println(Test.getLastMonthLastDay("yyyy-MM-dd HH:mm:ss"));
}
/**
* 获取上个月的第一天
* @return
*/
public static String getLastMonthFirstDay(String format ){
if(format == null || format.isEmpty()){
format = "yyyyMMdd";
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Calendar calendar = Calendar.getInstance();//获取当前日期
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
String firstDay = simpleDateFormat.format(calendar.getTime());
return firstDay;
}
/**
* 获取上个月的最后一天
* @return
*/
public static String getLastMonthLastDay(String format){
if(format == null || format.isEmpty()){
format = "yyyyMMdd";
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Calendar cale = Calendar.getInstance();
cale.set(Calendar.DAY_OF_MONTH,0);//设置为1号,当前日期既为本月第一天
String lastDay = simpleDateFormat.format(cale.getTime());
return lastDay;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
输出
2022-12-01 15:48:32
2022-12-31 15:48:32
2022-12-31 15:48:32
如果只想要年月日,可以对空格进行分割,时分秒用00:00:00代替即可。