java 怎样获取每个月的第一天和最后一天
发布网友
发布时间:2022-04-27 05:41
我来回答
共3个回答
热心网友
时间:2022-05-19 13:26
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//获取前月的第一天
Calendar cal_1=Calendar.getInstance();//获取当前日期
cal_1.add(Calendar.MONTH, -1);
cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
firstDay = format.format(cal_1.getTime());
System.out.println("-----1------firstDay:"+firstDay);
//获取前月的最后一天
Calendar cale = Calendar.getInstance();
cale.set(Calendar.DAY_OF_MONTH,0);//设置为1号,当前日期既为本月第一天
lastDay = format.format(cale.getTime());
System.out.println("-----2------lastDay:"+lastDay);
//获取当前月第一天:
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 0);
c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
String first = format.format(c.getTime());
System.out.println("===============first:"+first);
//获取当前月最后一天
Calendar ca = Calendar.getInstance();
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
String last = format.format(ca.getTime());
System.out.println("===============last:"+last);
追问能用循环写吗?从 18年1月开始到12月
热心网友
时间:2022-05-19 14:44
package com.test.packager;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Test {
private static String firstDay;
private static String lastDay;
public static void main(String[] args) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//获取前月的第一天
Calendar cal_1=Calendar.getInstance();//获取当前日期
cal_1.add(Calendar.MONTH, -1);
cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
firstDay = format.format(cal_1.getTime());
System.out.println("-----1------firstDay:"+firstDay);
//获取前月的最后一天
Calendar cale = Calendar.getInstance();
cale.set(Calendar.DAY_OF_MONTH,0);//设置为1号,当前日期既为本月第一天
lastDay = format.format(cale.getTime());
System.out.println("-----2------lastDay:"+lastDay);
//获取当前月第一天:
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 0);
c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
String first = format.format(c.getTime());
System.out.println("===============first:"+first);
//获取当前月最后一天
Calendar ca = Calendar.getInstance();
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
String last = format.format(ca.getTime());
System.out.println("===============last:"+last);
}
/**
* 字符串的日期格式的计算
*/
public static int daysBetween(String smdate,String bdate) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(smdate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(bdate));
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
}
热心网友
时间:2022-05-19 16:18
每个城市都有吧,成都当然也是有的,我家就是成都的,房子装修之后也做了甲醛治理,找的是绿色家缘,推荐