In project development, dates are an indispensable part of us. This article will summarize some common methods about dates in code development to facilitate your later use. The dishes are served directly below:
package com.example.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Common date methods* * @author * */ public class DateUtils { /** * Common variables*/ public static final String DATE_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_FORMAT_YMD = "yyyy-MM-dd"; public static final String DATE_FORMAT_HMS = "HH:mm:ss"; public static final String DATE_FORMAT_HM = "HH:mm"; public static final String DATE_FORMAT_YMDHM = "yyyy-MM-dd HH:mm"; public static final String DATE_FORMAT_YMDHMS = "yyyyMMddHHmmss"; public static final long ONE_DAY_MILLS = 3600000 * 24; public static final int WEEK_DAYS = 7; private static final int dateLength = DATE_FORMAT_YMDHM.length(); /** * Convert date to format string* * @param time * @param format * @return */ public static String formatDateToString(Date time, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(time); } /** * Convert the string to the format date* (Note: When the date you entered is 2014-12-21 12:12, the corresponding format should be yyyy-MM-dd HH:mm * Otherwise, the exception will be thrown) * @param date * @param format * @return * @throws ParseException * @ */ public static Date formatStringToDate(String date, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); try { return sdf.parse(date); } catch (ParseException ex) { ex.printStackTrace(); throw new RuntimeException(ex.toString()); } } /** * Determine whether a date belongs to two periods* @param time * @param timeRange * @return */ public static boolean isTimeInRange(Date time, Date[] timeRange) { return (!time.before(timeRange[0]) && !time.after(timeRange[1])); } /** * Time from the complete time to the minute* * @param fullDateStr * @return */ public static String getDateToMinute(String fullDateStr) { return fullDateStr == null ? null : (fullDateStr.length() >= dateLength ? fullDateStr.substring( 0, dateLength) : fullDateStr); } /** * Return all weeks of the specified year. List contains the String[2] object string[0] start date of the week, and string[1] is the end date of the week. * The date is in the format of YYYY-MM-DD The first week of each year must include Monday and be a complete seven days. * For example: The first week of 2009 starts at 2009-01-05 and the ends at 2009-01-11. Which year is Monday? Then what week is included in this week? * For example: 2008-12-29 is Monday, 2009-01-04 is Sunday, so this week is the last week of 2008. * * @param year * Format YYYY , must be greater than 1900 and less than 9999* @return @ */ public static List<String[]> getWeeksByYear(final int year) { int weeks = getWeekNumOfYear(year); List<String[]> result = new ArrayList<String[]>(weeks); int start = 1; int end = 7; for (int i = 1; i <= weeks; i++) { String[] tempWeek = new String[2]; tempWeek[0] = getDateForDayOfWeek(year, i, start); tempWeek[1] = getDateForDayOfWeek(year, i, end); result.add(tempWeek); } return result; } /** * Calculate the previous year and week of the specified year and week* * @param year * @param week * @return @ */ public static int[] getLastYearWeek(int year, int week) { if (week <= 0) { throw new IllegalArgumentException("The weekly number cannot be less than 1!!"); } int[] result = { week, year }; if (week == 1) { // previous year result[1] -= 1; // last week result[0] = getWeekNumOfYear(result[1]); } else { result[0] -= 1; } return result; } /** * Next [week, year] * * @param year * @param week * @return @ */ public static int[] getNextYearWeek(int year, int week) { if (week <= 0) { throw new IllegalArgumentException("The weekly number cannot be less than 1!!"); } int[] result = { week, year }; int weeks = getWeekNumOfYear(year); if (week == weeks) { // next year result[1] += 1; // first week result[0] = 1; } else { result[0] += 1; } return result; } /** * Calculate how many weeks there are in a specified year. (starts on Monday) * * @param year * @return @ */ public static int getWeekNumOfYear(final int year) { return getWeekNumOfYear(year, Calendar.MONDAY); } /** * Calculate how many weeks there are in a specified year. * * @param year * yyyy * @return @ */ public static int getWeekNumOfYear(final int year, int firstDayOfWeek) { // There are at least 52 weeks each year, and up to 53 weeks. int minWeeks = 52; int maxWeeks = 53; int result = minWeeks; int sIndex = 4; String date = getDateForDayOfWeek(year, maxWeeks, firstDayOfWeek); // To determine whether the year matches, if it matches, it means that there are 53 weeks. if (date.substring(0, sIndex).equals(year)) { result = maxWeeks; } return result; } public static int getWeeksOfWeekYear(final int year) { Calendar cal = Calendar.getInstance(); cal.setFirstDayOfWeek(Calendar.MONDAY); cal.setMinimalDaysInFirstWeek(WEEK_DAYS); cal.set(Calendar.YEAR, year); return cal.getWeeksInWeekYear(); } /** * Get the date corresponding to the day of the week of the specified year yyyy-MM-dd (starting from Monday) * * @param year * @param weekOfYear * @param dayOfWeek * @return yyyy-MM-dd Date in format @ */ public static String getDateForDayOfWeek(int year, int weekOfYear, int dayOfWeek) { return getDateForDayOfWeek(year, weekOfYear, dayOfWeek, Calendar.MONDAY); } /** * Get the date corresponding to the day of the week of the specified year yyyy-MM-dd, and specify the day of the week to calculate the first day of the week (firstDayOfWeek) * * @param year * @param weekOfYear * @param dayOfWeek * @param firstDayOfWeek * Specify the day of the week to calculate the first day of the week* @return yyyy-MM-dd Date in format */ public static String getDateForDayOfWeek(int year, int weekOfYear, int dayOfWeek, int firstDayOfWeek) { Calendar cal = Calendar.getInstance(); cal.setFirstDayOfWeek(firstDayOfWeek); cal.set(Calendar.DAY_OF_WEEK, dayOfWeek); cal.setMinimalDaysInFirstWeek(WEEK_DAYS); cal.set(Calendar.YEAR, year); cal.set(Calendar.WEEK_OF_YEAR, weekOfYear); return formatDateToString(cal.getTime(), DATE_FORMAT_YMD); } /** * Get the specified date of the week* * @param datetime * @throws ParseException * @ */ public static int getWeekOfDate(String datetime) throws ParseException { Calendar cal = Calendar.getInstance(); cal.setFirstDayOfWeek(Calendar.MONDAY); cal.setMinimalDaysInFirstWeek(WEEK_DAYS); Date date = formatStringToDate(datetime, DATE_FORMAT_YMD); cal.setTime(date); return cal.get(Calendar.DAY_OF_WEEK); } /** * Calculate all dates in a certain week of a certain year (from Monday to the first day of the week) * * @param yearNum * @param weekNum * @return @ */ public static List<String> getWeekDays(int yearNum, int weekNum) { return getWeekDays(yearNum, weekNum, Calendar.MONDAY); } /** * Calculate all dates in a certain week of a certain year (seven days) * * @param yearNum * @param weekNum * @return yyyy-MM-dd format date list*/ public static List<String> getWeekDays(int year, int weekOfYear, int firstDayOfWeek) { List<String> dates = new ArrayList<String>(); int dayOfWeek = firstDayOfWeek; for (int i = 0; i < WEEK_DAYS; i++) { dates.add(getDateForDayOfWeek(year, weekOfYear, dayOfWeek++, firstDayOfWeek)); } return dates; } /** * Get the year and week information of the target date for the previous week, this week, or next week* * @param queryDate * Incoming time* @param weekOffset * -1: Last week 0: This week 1: Next week* @param firstDayOfWeek * Which day of the week is the first day* @return * @throws ParseException */ public static int[] getWeekAndYear(String queryDate, int weekOffset, int firstDayOfWeek) throws ParseException { Date date = formatStringToDate(queryDate, DATE_FORMAT_YMD); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.setFirstDayOfWeek(firstDayOfWeek); calendar.setMinimalDaysInFirstWeek(WEEK_DAYS); int year = calendar.getWeekYear(); int week = calendar.get(Calendar.WEEK_OF_YEAR); int[] result = { week, year }; switch (weekOffset) { case 1: result = getNextYearWeek(year, week); break; case -1: result = getLastYearWeek(year, week); break; default: break; } return result; } /** * Calculate the number of days for two days* * @param startDate * Start date string* @param endDate * End date string* @return * @throws ParseException */ public static int getDaysBetween(String startDate, String endDate) throws ParseException { int dayGap = 0; if (startDate != null && startDate.length() > 0 && endDate != null && endDate.length() > 0) { Date end = formatStringToDate(endDate, DATE_FORMAT_YMD); Date start = formatStringToDate(startDate, DATE_FORMAT_YMD); dayGap = getDaysBetween(start, end); } return dayGap; } private static int getDaysBetween(Date startDate, Date endDate) { return (int) ((endDate.getTime() - startDate.getTime()) /ONE_DAY_MILLS); } /** * Calculate the difference in the number of days between two dates* @param startDate * @param endDate * @return */ public static int getDaysGapOfDates(Date startDate, Date endDate) { int date = 0; if (startDate != null && endDate != null) { date = getDaysBetween(startDate, endDate); } return date; } /** * Calculate the year gap between two dates* * @param firstDate * @param secondDate * @return */ public static int getYearGapOfDates(Date firstDate, Date secondDate) { if (firstDate == null || secondDate == null) { return 0; } Calendar helpCalendar = Calendar.getInstance(); helpCalendar.setTime(firstDate); int firstYear = helpCalendar.get(Calendar.YEAR); helpCalendar.setTime(secondDate); int secondYear = helpCalendar.get(Calendar.YEAR); return secondYear - firstYear; } /** * Calculate the month gap between two dates* * @param firstDate * @param secondDate * @return */ public static int getMonthGapOfDates(Date firstDate, Date secondDate) { if (firstDate == null || secondDate == null) { return 0; } return (int) ((secondDate.getTime() - firstDate.getTime()) /ONE_DAY_MILLS / 30); } /** * Calculate whether the current date is included * * @param datys * @return */ public static boolean isContainCurrent(List<String> dates) { boolean flag = false; SimpleDateFormat fmt = new SimpleDateFormat(DATE_FORMAT_YMD); Date date = new Date(); String dateStr = fmt.format(date); for (int i = 0; i < dates.size(); i++) { if (dateStr.equals(dates.get(i))) { flag = true; } } return flag; } /** * Calculate the date of the time queen from date* * @param date * @param time * @return * @throws ParseException */ public static String getCalculateDateToString(String startDate, int time) throws ParseException { String resultDate = null; if (startDate != null && startDate.length() > 0) { Date date = formatStringToDate(startDate, DATE_FORMAT_YMD); Calendar c = Calendar.getInstance(); c.setTime(date); c.set(Calendar.DAY_OF_YEAR, time); date = c.getTime(); resultDate = formatDateToString(date, DATE_FORMAT_YMD); } return resultDate; } /** * Get the week of the year that the specified date is calculated from a certain date* * @param date * @param admitDate * @return * @throws ParseException * @ */ public static int[] getYearAndWeeks(String date, String admitDate) throws ParseException { Calendar c = Calendar.getInstance(); c.setTime(formatStringToDate(admitDate, DATE_FORMAT_YMD)); int time = c.get(Calendar.DAY_OF_WEEK); return getWeekAndYear(date, 0, time); } /** * Get the specified date refDate, all dates of the week before or after * @param refDate * Reference date* @param weekOffset * -1: Last week 0: This week 1: Next week * @param startDate * Which day counts the first day of the week * @return yyyy-MM-dd Date * @throws ParseException * @ */ public static List<String> getWeekDaysAroundDate(String refDate, int weekOffset, String startDate) throws ParseException { // StartDate as the first day of the week Calendar c = Calendar.getInstance(); c.setTime(formatStringToDate(startDate, DATE_FORMAT_YMD)); int firstDayOfWeek = c.get(Calendar.DAY_OF_WEEK); // Get the corresponding week int[] weekAndYear = getWeekAndYear(refDate, weekOffset, firstDayOfWeek); // Get all dates of the corresponding week return getWeekDays(weekAndYear[1], weekAndYear[0], firstDayOfWeek); } /** * Get the time interval according to the time point* * @param hours * @return */ public static List<String[]> getTimePointsByHour(int[] hours) { List<String[]> hourPoints = new ArrayList<String[]>(); String sbStart = ":00:00"; String sbEnd = ":59:59"; for (int i = 0; i < hours.length; i++) { String[] times = new String[2]; times[0] = hours[i] + sbStart; times[1] = (hours[(i + 1 + hours.length) % hours.length] - 1) + sbEnd; hourPoints.add(times); } return hourPoints; } /** * Increase or decrease the number of days according to the specified date* * @param date * @param amount * @return */ public static Date addDays(Date date, int amount) { return add(date, Calendar.DAY_OF_MONTH, amount); } /** * Increase or decrease the number according to the specified date, type* * @param date * @param calendarField * @param amount * @return */ public static Date add(Date date, int calendarField, int amount) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar c = Calendar.getInstance(); c.setTime(date); c.add(calendarField, amount); return c.getTime(); } /** * Get the maximum date time of the current date 2014-12-21 23:59:59 * @return */ public static Date getCurDateWithMaxTime() { Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, 23); c.set(Calendar.MINUTE, 59); c.set(Calendar.SECOND, 59); return c.getTime(); } /** * Get the minimum date time of the current date2014-12-21 00:00:00 * @return */ public static Date getCurDateWithMinTime() { Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); return c.getTime(); } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.