在做图表的检索时,经常会用到检索的时间条件,时间格式的不同,以及间隔不同。因此总结了一套
/***
*获得本月第一天
****/
public static String getMonthFirstDay() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 0);
c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
String first = format.format(c.getTime());
return first;
}
/***
*获得本月最后一天
****/
public static String getMonthyLastDay() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar ca = Calendar.getInstance();
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
String last = format.format(ca.getTime());
return last;
}
/****
*
* 获得时间往前推1年
* ***/
public static String getLastYear() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar ca = Calendar.getInstance();
ca.set(Calendar.YEAR, -1);
String last = format.format(ca.getTime());
return last;
}
/**
* yyyy-MM-dd
*/
public static final String YEAR_TO_DAY = "yyyy-MM-dd";
/**
* yyyy-MM-dd HH:mm:ss
*/
public static final String YEAR_TO_SECOND = "yyyy-MM-dd HH:mm:ss";
public static String formatDate(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(new Date());
}
public static String formatDate(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
public static String formatTomorrowDate(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 1);
return sdf.format(calendar.getTime());
}
public static int compare(Date date1, Date date2) {
return date1.compareTo(date2);
}
public static int compare(String date1, String format, Date date2) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = sdf.parse(date1);
return date.compareTo(date2);
}
public static Date parse(String date, String format) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.parse(date);
}
public static Date parse(String date, String format, Locale locale, TimeZone timeZone) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
sdf.setTimeZone(timeZone);
return sdf.parse(date);
}
public static Date getNextDate(String hourToSecond) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(YEAR_TO_DAY);
Date date = sdf.parse(DateUtil.formatDate(YEAR_TO_DAY) + " " + hourToSecond);
return date;
}
public static Date getCurrentDateRandomSecond(String hourToSecond) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(YEAR_TO_SECOND);
String[] fields = hourToSecond.split("\\:");
Integer randomSecond = RandomUtils.nextInt(59);
String second = (randomSecond.toString().length() == 1 ? "0" + randomSecond : randomSecond + "");
String date = DateUtil.formatDate(YEAR_TO_DAY) + " " + fields[0] + ":" + fields[1] + ":" + second;
return sdf.parse(date);
}
public static Date getNextDateRandomSecond(String hourToSecond) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(YEAR_TO_SECOND);
String[] fields = hourToSecond.split("\\:");
Integer randomSecond = RandomUtils.nextInt(59);
String second = (randomSecond.toString().length() == 1 ? "0" + randomSecond : randomSecond + "");
String date = DateUtil.formatTomorrowDate(YEAR_TO_DAY) + " " + fields[0] + ":" + fields[1] + ":" + second;
return sdf.parse(date);
}
public static String formatDateCHS(Date date) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
StringBuilder str = new StringBuilder();
str.append(calendar.get(Calendar.YEAR));
str.append("年");
str.append(calendar.get(Calendar.MONTH) + 1);
str.append("月");
str.append(calendar.get(Calendar.DAY_OF_MONTH));
str.append("日");
return str.toString();
}
/**
* 获取之后的?天
*
* @param today 传入的当前天
* @param i 需要相加的天数
* @return
*/
@SuppressWarnings("static-access")
public static String getNextDay(String today, int i) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date dd = new Date();
try {
dd = formatter.parse(today);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = new GregorianCalendar();
calendar.setTime(dd);
calendar.add(calendar.DATE, i);// 把日期往后增加一天.整数往后推,负数往前移动
dd = calendar.getTime(); // 这个时间就是日期往后推一天的结果
String dateString = formatter.format(dd);
return dateString;
}
/**
* 获取传入参数之后的?天
*
* @param today 传入的当前天
* @param i 需要相加的天数
* @param YYYY/MM/DD
* @return
*/
@SuppressWarnings("static-access")
public static String getBeforeDay(String today, int i) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date dd = new Date();
try {
dd = formatter.parse(today);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = new GregorianCalendar();
calendar.setTime(dd);
calendar.add(calendar.DATE, i);// 把日期往后增加一天.整数往后推,负数往前移动
dd = calendar.getTime(); // 这个时间就是日期往后推一天的结果
String dateString = formatter.format(dd);
return dateString;
}
/**
* 获取传入参数之后的?年
*
* @param today 传入的当前天
* @param i 需要相加年数
* @return
*/
@SuppressWarnings("static-access")
public static String getNextYear(String today, int i) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date dd = new Date();
try {
dd = formatter.parse(today);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = new GregorianCalendar();
calendar.setTime(dd);
calendar.add(calendar.YEAR, i);// 把日期往后增加一年.整数往后推,负数往前移动
dd = calendar.getTime(); // 这个时间就是日期往后推一年的结果
String dateString = formatter.format(dd);
return dateString;
}
/**
* 获取传入参数之后的?年
*
* @param today 传入的当前天
* @param i 需要相加年数
* @return
*/
@SuppressWarnings("static-access")
public static Date getNextYearOnDate(String today, int i) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date dd = new Date();
try {
dd = formatter.parse(today);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = new GregorianCalendar();
calendar.setTime(dd);
calendar.add(calendar.YEAR, i);// 把日期往后增加一年.整数往后推,负数往前移动
dd = calendar.getTime(); // 这个时间就是日期往后推一天的结果
return dd;
}
/**
* 获取传入参数之后的?天
*
* @param today 传入的当前天
* @param i 需要相加的天数
* @return
*/
@SuppressWarnings("static-access")
public static Date getNextDayonDate(String today, int i) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date dd = new Date();
try {
dd = formatter.parse(today);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = new GregorianCalendar();
calendar.setTime(dd);
calendar.add(calendar.DATE, i);// 把日期往后增加一天.整数往后推,负数往前移动
dd = calendar.getTime(); // 这个时间就是日期往后推一天的结果
return dd;
}
public static Date getNextDay(Date date, int i) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, i);
date = calendar.getTime();
return date;
}
public static Date getNextYear(Date date, int i) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.YEAR, i);
date = calendar.getTime();
return date;
}
/**
* 获取指定周期之前的时刻
*
* @param endTime
* @param period
* @return
*/
public static long getBeforPeriodTimestamp(long endTime, DateUtil.Period period) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(endTime);
calendar.add(period.getCalendarField(), 0 - period.getAmount());
return calendar.getTimeInMillis();
}
;
/**
* 获取指定周期之前的时长
*
* @param endTime
* @param period
* @return
*/
public static long getBeforPeriodDuration(long endTime, DateUtil.Period period) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(endTime);
calendar.add(period.getCalendarField(), 0 - period.getAmount());
return endTime - calendar.getTimeInMillis();
}
;
public enum Period {
/**
* 一天
*/
ONE_DAY("一天", Calendar.DAY_OF_MONTH, 1),
/**
* 一天
*/
TWO_DAY("两天", Calendar.DAY_OF_MONTH, 2),
/**
* 一天
*/
THREE_DAY("三天", Calendar.DAY_OF_MONTH, 3),
/**
* 一天
*/
ONE_WEEK("一星期", Calendar.WEEK_OF_MONTH, 1),
/**
* 一天
*/
TWO_WEEK("两星期", Calendar.WEEK_OF_MONTH, 2),
/**
* 一天
*/
THREE_WEEK("三星期", Calendar.WEEK_OF_MONTH, 3),
/**
* 一天
*/
ONE_MONTH("一月", Calendar.MONTH, 1);
private Period(String name, int calendarField, int amount) {
this.name = name;
this.calendarField = calendarField;
this.amount = amount;
}
private String name;
private int calendarField;
private int amount;
public String getName() {
return this.name;
}
public int getCalendarField() {
return calendarField;
}
public int getAmount() {
return amount;
}
}
/**
* @param time
* @param format
* @return
*/
public static String format(Long time, String format) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
return DateUtil.formatDate(calendar.getTime(), format);
}
public static boolean isWorkDay(Calendar calendar) {
return !(calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY);
}
/**
* @param date
* @return
*/
public static boolean isWorkDay(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return isWorkDay(c);
}
/**
* @param year
* @return
*/
public static final boolean isGregorianLeapYear(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
/**
* @param mon
* @return
*/
public static final String addMonth(int mon) {
return mon + 1 < 10 ? "0" + (mon + 1) : (mon + 1) + "";
}
/**
* @param day
* @return
*/
public static final String addDay(int day) {
return day < 10 ? "0" + day : day + "";
}
/**
* getDateTimeTicks(这里用一句话描述这个方法的作用)
* java时间转C#时间
*
* @param @return 设定文件
* @return String DOM对象
* @Exception 异常对象
* @since CodingExample Ver(编码范例查看) 1.1
*/
public static long getDateTimeTicks() {
//C# DateTime.Now.Ticks属性的值表示自 0001 年 1 月 1 日午夜 12:00:00(表示 DateTime.MinValue)以来经过的以 100 纳秒为间隔的间隔数
long timeticks;
//1979与0001相隔毫秒数 (1979-0001)*365*24*60*60*1000
long time_JAVA_Long = Long.parseLong("62378208000000");
//java长整型日期,毫秒为单位
Date dt_1979 = new Date();
//long型的毫秒数
long tricks_1979 = dt_1979.getTime();
//1970年1月1日刻度
long time_tricks = (tricks_1979 + time_JAVA_Long) * 10000;
timeticks = time_tricks;
return timeticks;
}
/**
* getDayCountOfMonth
* 取某年某月的天數
*
* @param date 日期YYYYMMDD
* @return int 月的天數
* @Exception 异常对象
*/
public static int getDayCountOfMonth(String date) {
try {
if (StringUtil.isEmpty(date)) {
return 0;
}
switch (date.substring(4, 6)) {
case "01":
case "03":
case "05":
case "07":
case "08":
case "10":
case "12":
return 31;
case "04":
case "06":
case "09":
case "11":
return 30;
case "02":
//润年
if (isGregorianLeapYear(Integer.parseInt(date.substring(0, 4)))) {
return 29;
} else {
return 28;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
TimeUtils 实体类共通的方法
/**
* 获取前n天日期和相应星期数
*
* @return 日期和相应星期数
*/
public static Map getweektime(String d) {
Map retMap = new HashMap();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -Integer.parseInt(d));
Date monday = c.getTime();
String week = getWeekOfDate(monday);
String preMonday = sdf.format(monday);
retMap.put("week", week);
retMap.put("time", preMonday);
SimpleDateFormat MM = new SimpleDateFormat("M");
SimpleDateFormat dd = new SimpleDateFormat("dd");
String MM1 = MM.format(monday);
String dd1 = dd.format(monday);
String res = MM1 + "月" + dd1 + "日";
retMap.put("monDay", res);
return retMap;
}
/**
* 获取当前日期是星期几
*
*
*/
public static String getWeekOfDate(Date dt) {
String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}
/**
* 日期格式化为xxxx年xx月xx日 xx:xx:xx
*
* @param date
*/
public static String formmaterDateTimeStringToString(String datetime) {
String result = "";
if (null != datetime && !datetime.isEmpty()) {
result = datetime.substring(0, 16).replace(" ", "-").replace(":", "-");
if (null != result && !result.isEmpty()) {
String[] arrtime = result.split("-");
if (null != arrtime) {
result = arrtime[1] + "月" + arrtime[2] + "日 " + arrtime[3] + "时" + arrtime[4] + "分";
}
}
}
return result;
}
/**
* 获取前n天的日期 2种表现方式
*
* @return 前n天的日期 2种表现方式
*/
public static Map getStatetime(int daynum) throws ParseException {
Map retMap = new HashMap();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -daynum);
Date monday = c.getTime();
String pretime = sdf.format(monday);
String preDay = sdf2.format(monday);
retMap.put("time", pretime);
retMap.put("preDay", preDay);
return retMap;
}
/**
* 获取两个日期之间的日期
*
* @param start 开始日期
* @param end 结束日期
* @return 日期集合
*/
public static List getBetweenDates(String inpstart, String inpend) {
//时间转换类
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date start = null;
Date end = null;
try {
start = sdf.parse(inpstart);
end = sdf.parse(inpend);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List result = new ArrayList();
result.add(inpstart);
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
tempStart.add(Calendar.DAY_OF_YEAR, 1);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
while (tempStart.before(tempEnd)) {
result.add(sdf.format(tempStart.getTime()));
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
result.add(inpend);
return result;
}
/**
* 获取两个日期之间的日期
*
* @param start 开始日期
* @param end 结束日期
* @return 日期集合
*时间格式为YYYYMMDD
*/
public static List getBetweenRealDates(String inpstart, String inpend) {
//时间转换类
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date start = null;
Date end = null;
try {
start = sdf.parse(inpstart);
end = sdf.parse(inpend);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List result = new ArrayList();
result.add(inpstart);
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
tempStart.add(Calendar.DAY_OF_YEAR, 1);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
while (tempStart.before(tempEnd)) {
result.add(sdf.format(tempStart.getTime()));
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
result.add(inpend);
return result;
}
/**
* 获取一个日期的月日
*
* @param start 开始日期
* @param end 结束日期
* @return 日期
*/
public static String getDateDay(String time) {
//时间转换类
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd");
Date temptime = null;
try {
temptime = sdf.parse(time);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String DateDay = sdf2.format(temptime);
return DateDay;
}
/**
* 获取一个月的所有日期
*
* @param start 开始日期
* @return 日期
*/
public static String[] getMonthDays(String date) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, Integer.parseInt(date.substring(0, 4)));
calendar.set(Calendar.MONTH, Integer.parseInt(date.substring(5, 7)) - 1);
int month = Integer.parseInt(date.substring(5, 7));
int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
String[] days = new String[maxDay];
for (int i = 1; i <= maxDay; i++) {
days[i - 1] = String.valueOf(month) + "月" + String.valueOf(i) + "日";
}
return days;
}
/**
* 获取输入日期的前7天
*
* @param date 开始日期
*/
public static String[] getSevenDays(String date) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, Integer.parseInt(date.substring(0, 4)));
calendar.set(Calendar.DATE, Integer.parseInt(date.substring(5, 7)) - 1);
int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_WEEK);//maxDay-----7天
String[] days = new String[maxDay];
for (int i = 1; i <= maxDay; i++) {
days[i - 1] = DateUtil.getBeforeDay(date, i - 8);
}
return days;
}
/**
* 获取当前日期是星期几
* @return 当前日期是星期几
*/
public static int getWeekNum(String time) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date temptime = null;
try {
temptime = sdf.parse(time);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(temptime);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return w;
}
/**
* 获取当前日期格式,由YYYY/MM/DD--》YYYYMMDD
* @return 当前日期是星期几
*/
public static String UpdateFormat(String time) {
String newtime = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
if (null != time && !time.isEmpty()) {
try {
Date temptime = null;
try {
temptime = (Date) sdf.parse(time);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
newtime = sdf2.format(temptime);
} catch (ParseException e) {
e.printStackTrace();
}
}
return newtime;
}
/**
* 获取当前日期格式,由YYYYMMDD--》YYYY/MM/DD
* @return 当前日期是星期几
*/
public static String UpdateDateFormat(String time) {
String newtime = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");
if (null != time && !time.isEmpty()) {
try {
Date temptime = null;
try {
temptime = (Date) sdf.parse(time);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
newtime = sdf2.format(temptime);
} catch (ParseException e) {
e.printStackTrace();
}
}
return newtime;
}
/**
* 获取当前日期格式,由YYYY/MM--》YYYYMM
* @return 当前日期是星期几
*/
public static String UpdateFormatMonth(String time) {
String newtime = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMM");
try {
Date temptime = null;
try {
temptime = (Date) sdf.parse(time);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
newtime = sdf2.format(temptime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newtime;
}
/**
* 获取当前日期格式,由YYYY-MM-DD--》YYYYMMDD
* @return 当前日期是星期几
*/
public static String UpdateFormatReal(String time) {
String newtime = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
if (null != time && !time.isEmpty()) {
try {
Date temptime = null;
try {
temptime = (Date) sdf.parse(time);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
newtime = sdf2.format(temptime);
} catch (ParseException e) {
e.printStackTrace();
}
}
return newtime;
}