package com.boying.common.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class DateUtil { public static Date stringDateFormat(String strDate, String format) { if (StringUtil.isNullOrEmpty(strDate)) { return null; } SimpleDateFormat sdf = null; if (format == null) sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); else sdf = new SimpleDateFormat(format); try { return sdf.parse(strDate); } catch (ParseException e) { return null; } } public static String DateToString(Date date,String format){ if(!StringUtil.isNullOrEmpty(format)){ SimpleDateFormat f = new SimpleDateFormat(format); String sDate = f.format(date); return sDate; } SimpleDateFormat f = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); String sDate = f.format(date); return sDate; } public static Date getYearFirst(int year){ Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); Date currYearFirst = calendar.getTime(); return currYearFirst; } /** * 获取某年最后一天日期 * @param year 年份 * @return Date */ public static Date getYearLast(int year){ Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.roll(Calendar.DAY_OF_YEAR, -1); Date currYearLast = calendar.getTime(); return currYearLast; } /** * 获取指定年月的第一天 * @param year * @param month * @return */ public static Date getFirstDayOfMonth(int year, int month) { Calendar cal = Calendar.getInstance(); //设置年份 cal.set(Calendar.YEAR, year); //设置月份 cal.set(Calendar.MONTH, month-1); //获取某月最小天数 int firstDay = cal.getMinimum(Calendar.DATE); //设置日历中月份的最小天数 cal.set(Calendar.DAY_OF_MONTH,firstDay); return cal.getTime(); } /** * 获取指定年月的最后一天 * @param year * @param month * @return */ public static Date getLastDayOfMonth(int year, int month) { Calendar cal = Calendar.getInstance(); //设置年份 cal.set(Calendar.YEAR, year); //设置月份 cal.set(Calendar.MONTH, month-1); //获取某月最大天数 int lastDay = cal.getActualMaximum(Calendar.DATE); //设置日历中月份的最大天数 cal.set(Calendar.DAY_OF_MONTH, lastDay); return cal.getTime(); } public static String getFirstTimeByDate() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); String start_update = format.format(cal.getTime()); cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY)-1); String end_update = format.format(cal.getTime()); return end_update; } public static Date getToDayFirstDate() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); //String start_update = format.format(cal.getTime()); cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY)-1); //String end_update = format.format(cal.getTime()); return cal.getTime(); } }