Tools for time management (date shift, date format, get day of the week, etc.)

1. Return the specified date format (string format)

 public static String getDate(Date date, String format) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat sdFormat = new SimpleDateFormat(format);

        return sdFormat.format(date);
    }

1.1, return the specified date (date format)

 public static Date getDate(String date, String format) {
        try {
            return new SimpleDateFormat(format).parse(date);
        } catch (Exception e) {
            //e.printStackTrace();
            return null;
        }
    }

2. Date shift

 public static Date moveDate(Date date, int moveDistance) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, moveDistance);
        return calendar.getTime();
    }

3. Yearly shift

 public static Date moveYear(Date date, int moveYear) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, moveYear);
        return calendar.getTime();
    }

4. Shift by month

 public static Date moveMonth(Date date, int moveDistance) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, moveDistance);
        return calendar.getTime();
    }

5. Shift by minutes

public static Date moveMinute(Date date, int moveDistance) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, moveDistance);
        return calendar.getTime();
    }

6. Pan by second

public static Date moveSecond(Date date, int moveDistance) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.SECOND, moveDistance);
        return calendar.getTime();
    }

7. What day of the week to return

 public static String getWeekDay(Date date) {
        SimpleDateFormat sdFormat = new SimpleDateFormat("EEEE");
        return sdFormat.format(date);
    }
 public static String getWeekDay(String date, String format) {
        //这里的getDate在上面有写
        return getWeekDay(getDate(date, format));
    }

8. Query the first day of the month where the current day is

public static Date getMonthFirstDate(Date date) {
        return getDate((new SimpleDateFormat("yyyy-MM").format(date) + "-01"),
                "yyyy-MM-dd");
    }

 

Guess you like

Origin blog.csdn.net/qq_36138652/article/details/108241417