标签:format alc nbsp get 实例 vat pre tar actual
1、日期的加减操作
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateCalculate { private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * 获取形如yyyy-MM-dd HH:mm:ss * @param date * @return */ public static String datetimeToString(Date date) { return sdf.format(date); } /** * 根据时间字符串获取日期 * @param dateString * @return * @throws ParseException */ public static Date stringToDatetime(String dateString) throws ParseException { return sdf.parse(dateString); } /** * 获取本月最后一天 * @return */ public static Date getMonthStartDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH,1); return calendar.getTime(); } /** * 获取本月最后一天 * @return */ public static Date getMonthEndDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); return calendar.getTime(); } /** * 获取指定日期所属周的开始时间 * @param date * @return */ public static Date getBeginWeekDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == 1) { dayOfWeek += 7; } cal.add(Calendar.DATE,2 - dayOfWeek); return cal.getTime(); } /** * 距离指定日期所属周结束时间 * @return */ public static Date getEndWeekDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == 1) { dayOfWeek += 7; } cal.add(Calendar.DATE,8 - dayOfWeek); return cal.getTime(); } /** * 对指定日期进行年份加减操作 * @param date * @param num * @return */ public static Date calculateDateOfYear(Date date,Integer num) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.YEAR,num); return calendar.getTime(); } /** * 对指定日期月份进行加减操作 * @param date * @param num * @return */ public static Date calculateDateOfMonth(Date date,Integer num) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH,num); return calendar.getTime(); } /** * 对指定日期天数进行加减操作 * @param date * @param num 负整数 正整数 * @return */ public static Date calculateDateOfDay(Date date,Integer num) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH,num); return calendar.getTime(); } public static void main(String[] args) throws ParseException { System.out.println(datetimeToString(getMonthStartDate(sdf.parse("2019-12-04 12:09:52")))); System.out.println(datetimeToString(getEndWeekDate(sdf.parse("2019-12-04 12:09:52")))); System.out.println(datetimeToString(calculateDateOfYear(stringToDatetime("2019-12-04 12:09:52"),-2))); } }
标签:format alc nbsp get 实例 vat pre tar actual
原文地址:https://www.cnblogs.com/snow-wolf-1/p/12001370.html