1.获取年月
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONDAY)+1;//月份需+1
System.out.println(year+" "+month);
输出
2020 9
2.Date转为格式化字符串
Date now = new Date();
DateFormat t = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
String time = t.format(now);
System.out.println(time);
输出:
2020-09-09 14:30:43
3.字符串转为格式Date对象
Date now = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
String dateStr = dateFormat.format(now);
try {
blindPlateEntity.setGmtCreate(dateFormat.parse(dateStr));
} catch (ParseException e) {
e.printStackTrace();
}
4、判断日期字符串是否为周末
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @description: 判断日期字符串是否为周末
*/
public class IsWeekend {
public boolean isWeekend(String dateStr) {
boolean isWeekend = false;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = sdf.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
isWeekend = cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
} catch (ParseException e) {
e.printStackTrace();
}
return isWeekend;
}
}
5、time时间戳转Date
/**
* time时间戳转Date
*
* @param time
* @return
*/
public static Date timeToDate(String time) {
SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdfTime.format(Long.valueOf(time));
try {
Date date = sdfTime.parse(str);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
6、将时间转为core表达式
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println(formatDateByPattern(calendar.getTime(), "ss mm HH dd MM ? yyyy"));
calendar.add(Calendar.MINUTE, 5);
System.out.println(formatDateByPattern(calendar.getTime(), "ss mm HH dd MM ? yyyy"));
}
/**
* 将日期转化为对应的格式
* @param date
* @param dateFormat
* @return
*/
public static String formatDateByPattern(Date date, String dateFormat){
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
String formatTimeStr = null;
if (date != null) {
formatTimeStr = sdf.format(date);
}
return formatTimeStr;
}
7、反解析core表达式
CronExpression cronExpression = new CronExpression(cronExpressionString);
// 反解析下一次的执行时间
Date nextDate = cronExpression.getNextValidTimeAfter(new Date((1997)));
long nextTime = nextDate.getTime();