import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * @Author chenrd * @Date 2021-6-7 上午11:02:03 * @Version 1.0 业务说明:本类默认时间格式采用yyyy-MM-dd * */ public class MyTimeUtil { public static String fmtTime="yyyy-MM-dd"; public static String fmtTimeStamp="yyyy-MM-dd HH:mm:ss"; public static SimpleDateFormat sdf = new SimpleDateFormat(fmtTime); public static SimpleDateFormat sdfTime = new SimpleDateFormat(fmtTimeStamp); public static void main(String[] args) { } /** * 字符串的日期加上一天,在返回字符串 */ public static String addOneDay(String countdate) throws Exception { Calendar c = Calendar.getInstance(); c.setTime(sdf.parse(countdate)); c.add(Calendar.DATE, 1); String rtn = sdf.format(c.getTime()); return rtn; } /** * 字符串的日期加上一天,在返回字符串 */ public static String subOneDay(String countdate) throws Exception { Calendar c = Calendar.getInstance(); c.setTime(sdf.parse(countdate)); c.add(Calendar.DATE, -1); String rtn = sdf.format(c.getTime()); return rtn; } /** * @param countdate * @param num (负数就是减,正数就是加) * @return 字符串的日期加上自定义天,在返回字符串 * @throws Exception * String * */ public static String addSomeDay(String countdate,int num) throws Exception { Calendar c = Calendar.getInstance(); c.setTime(sdf.parse(countdate)); c.add(Calendar.DATE, num); String rtn = sdf.format(c.getTime()); return rtn; } /** * @param countdate * @return 返回年第一天,如2021-01-01 * @throws Exception * String * */ public static String getYearfirstDay(String countdate) throws Exception { String rtn = countdate.substring(0, countdate.length() - 5) + "01-01"; return rtn; } /** * @param countdate * @return 返回年最后一天,如2021-12-12 * @throws Exception * String * */ public static String getYearLastDay(String countdate) throws Exception { String rtn = countdate.substring(0, countdate.length() - 5) + "12-12"; return rtn; } /** * 获取当月第一天(传参) * * @return * @throws ParseException */ public static Date getMonthFirstDay(String rq) throws ParseException { Calendar ca = Calendar.getInstance(); ca.setTime(new SimpleDateFormat(fmtTime).parse(rq)); ca.set(Calendar.DAY_OF_MONTH, ca.getActualMinimum(Calendar.DAY_OF_MONTH)); return ca.getTime(); } /** * 获取当月最后一天(传参) * * @return * @throws ParseException */ public static Date getMonthLastDay(String rq) throws ParseException { Calendar ca = Calendar.getInstance(); ca.setTime(new SimpleDateFormat(fmtTime).parse(rq)); ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH)); return ca.getTime(); } /** * 获取当前星期几 * 调用方法, week(c.get(Calendar.DAY_OF_WEEK)) * @return */ public String week(int i) { String[] week = new String[] { "星期日","星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; return week[i-1]; } }