Calendar的用法:
//Calendar初始化 Calendar c = Calendar.getInstance(); //Calendar设置时间 c.setTime(new Date()); //在给定的日历字段中添加或减去指定的时间 c.add(Calendar.DATE, - 7); //Calendar中获取时间戳 long ts = c.getTimeInMillis(); //Calendar转为Date格式 Date d = c.getTime(); //SimpleDateFormat格式化Date类型 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String day = format.format(d); //2022-01-27 13:40:00格式的字符串转为Date格式(字符串转Date类型) Date date = simpleDateFormat.parse("2022-01-27 13:40:00"); //从date格式中获取时间戳 long ts = date.getTime()
package com.zydl.safeQuartz.common.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* --日期转换工具--
* auth: YH
* date: 2021.12.03
* */
public class CalendarUtil {
// 1.获取过去七天的日期
public static String LastWeek(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, - 7);
Date d = c.getTime();
String day = format.format(d);
return day;
}
// 2.获取过去七天的时间戳
public static String LastWeekStamp(){
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, - 7);
long ts = c.getTimeInMillis();
String res = String.valueOf(ts);
return res;
}
// 3.获取过去一月的日期
public static String LastMonth(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.MONTH, -1);
Date m = c.getTime();
String mon = format.format(m);
return mon;
}
// 4.获取过去一年的日期
public static String LastYear(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.YEAR, -1);
Date y = c.getTime();
String year = format.format(y);
return year;
}
// 5.获取过去30秒的日期
public static Long LastSec30(){
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.SECOND, - 30);
Date d = c.getTime();
long ts = d.getTime();
return ts;
}
// 6.获取过去1分钟的日期
public static Long LastMI10(){
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.MINUTE, - 10);
Date d = c.getTime();
long ts = d.getTime();
return ts;
}
}