格式转换
SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sim3 = new SimpleDateFormat("yyyy-MM");
SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat sim2 = new SimpleDateFormat("HH:mm");
Date da =new Date();
String time2 = sim2.format(da);
String time2 = sim2.parse(time2)
时间戳 转换成时间
Date da =new Date();
da.setTime(1614132240000l);
String time2 = sim2.format(da);
比较时间大小
String beginTime=new String("2017-06-09 10:22:22");
String endTime=new String("2017-05-08 11:22:22");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date sd1=df.parse(beginTime);
Date sd2=df.parse(endTime);
System.out.println(sd1.before(sd2));
System.out.println(sd1.after(sd2));
用String的compareTo()方法: 返回正值是代表左侧日期大于参数日期,反之亦然,日期格式必须一致
Integer i=beginTime.compareTo(endTime);
System.out.println(i);
转成date格式换成秒数比较秒数大小,getTime()方法
Date sd1=df.parse(beginTime);
Date sd2=df.parse(endTime);
long long1 =sd1.getTime()
long long2= sd2.getTime()
获取今天的昨天 明天
Date da =new Date();
Calendar c = Calendar.getInstance();
c.setTime(da);
int day2 = da.getDay(); //获取 周几
System.out.println("day2----"+day2);
c.add(Calendar.DAY_OF_MONTH, 1);
Date tomorrow = c.getTime();
System.out.println("tomorrow"+tomorrow+"==="+sim.format(tomorrow));
c.setTime(da);
c.add(Calendar.DAY_OF_MONTH, -1);
Date yesterday = c.getTime();
System.out.println("yesterday :"+yesterday+"==========="+sim.format(yesterday));
List<String> date_list = getDateListBetween2Day(2021 + "-" + 1 + "-01",
2021 + "-" + 1 + "-" + 31, "yyyy-MM-dd"); // 获取指定格式内的所有天数
获取 某月有多少天
Calendar c = Calendar.getInstance();
c.set(2021, 3, 0); // 3 月份 0 获取本月所有天数 不为零时 获取本月到这一天 的天数 如 28号 本月到28号 28天
int day_size = c.get(Calendar.DAY_OF_MONTH);// 当前月有多少天
遍历出指定格式的所有天数
public static ArrayList<String> getDateListBetween2Day(String stime,String etime,String date_pattern) throws ParseException{
ArrayList<String> list= new ArrayList<String>();
SimpleDateFormat df=new SimpleDateFormat(date_pattern);
Calendar cal = Calendar.getInstance();
Date sdate=df.parse(stime);
Date edate=df.parse(etime);
cal.setTime(sdate);
while(edate.after(sdate)) {
list.add(df.format(sdate));
cal.add(Calendar.DAY_OF_MONTH,1);
sdate=cal.getTime();
}
list.add(df.format(edate));
return list;
}