日期操作java和js类

日期操作java和js类 比如某月第一天和最后一天

1.java

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;


import javax.xml.crypto.Data;


import org.apache.commons.io.EndianUtils;


public class DateUtil {
private static final String defaultFormat = "yyyy-MM-dd HH:mm:ss";


private static final SimpleDateFormat MONTH_SDF = new SimpleDateFormat("yyyy-MM");


private static final SimpleDateFormat DAY_SDF = new SimpleDateFormat("yyyy-MM-dd");


public static Date getDate(String text, String format) {


SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = null;


try {
date = sdf.parse(text);
} catch (ParseException e) {
e.printStackTrace();
}


return date;


}


public static Date getDate(String text) {
return getDate(text, defaultFormat);
}


public static String fmtDate(Date date) {
return fmtDate(date, defaultFormat);
}


public static String fmtDate(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);


return sdf.format(date);


}


public static java.sql.Date getSQLDate(String text, String format) {
if (text == null || "".equals(text)) {
return null;
}


long time = getDate(text, format).getTime();
return new java.sql.Date(time);


}


public static java.sql.Timestamp getTimestamp(Date date) {
return new java.sql.Timestamp(date.getTime());
}


/**
* 获取当月第一天'yyyy-MM' 空或不支持格式返回当前月第一天

* @param date
*            yyyy-MM
* @return 'yyyy-MM-dd'
*/
public static String getMonthFirstDay(String date) {


Date theDate;
try {
theDate = MONTH_SDF.parse(date);
} catch (ParseException e) {
e.printStackTrace();
theDate = new Date();
}
return getMonthFirstDay(theDate);


}


/**
* 获取当月第一天'yyyy-MM' 空或不支持格式返回当前月第一天

* @param date
* @return 'yyyy-MM-dd'
*/
public static String getMonthFirstDay(Date date) {
return DAY_SDF.format(getFirstDayDate(date));
}


/**
* 获取当月第一天'yyyy-MM' 空或不支持格式返回当前月第一天

* @param date
* @return 'yyyy-MM-dd'
*/
public static Date getFirstDayDate(Date date) {
GregorianCalendar c = (GregorianCalendar) Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_MONTH, 1);
return c.getTime();


}


// 获得下个月第一天的日期
public static String getNextMonthFirst() {
String str = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar lastDate = Calendar.getInstance();
lastDate.add(Calendar.MONTH, 1);// 减一个月
lastDate.set(Calendar.DATE, 1);// 把日期设置为当月第一天
str = sdf.format(lastDate.getTime());
return str;
}


// 获得下个月最后一天的日期
public static String getNextMonthEnd() {
String str = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar lastDate = Calendar.getInstance();
lastDate.add(Calendar.MONTH, 1);// 加一个月
lastDate.set(Calendar.DATE, 1);// 把日期设置为当月第一天
lastDate.roll(Calendar.DATE, -1);// 日期回滚一天,也就是本月最后一天
str = sdf.format(lastDate.getTime());
return str;
}


/**
* 获取当月最后一天'yyyy-MM' 空或不支持格式返回当前月最后一天

* @param date
* @return 'yyyy-MM-dd'
*/
public static String getMonthLastDay(String date) {
Date theDate;
try {
theDate = MONTH_SDF.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
theDate = new Date();
}
return getMonthLastDay(theDate);
}


/**
* 获取当月最后一天'yyyy-MM' 空或不支持格式返回当前月最后一天

* @param date
* @return 'yyyy-MM-dd'
*/
public static String getMonthLastDay(Date date) {
return DAY_SDF.format(getLastDayDate(date));
}
/**
* 得到最后一天的日期

* @param date
* @return
*/
public static Date getLastDayDate(Date date) {
GregorianCalendar c = (GregorianCalendar) Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_MONTH, 1);
c.roll(Calendar.DAY_OF_MONTH, -1);
return c.getTime();
}


/**
* 日期添加相应天数

* @param date
* @return 'yyyy-MM-dd'
*/
public static Date addDay(Date date, int increaseNum) {
GregorianCalendar c = (GregorianCalendar) Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_MONTH, increaseNum);
return c.getTime();
}


/**
* 日期添加相应天数

* @param date
* @return 'yyyy-MM-dd'
*/
public static Date addMonth(Date date, int increaseNum) {
GregorianCalendar c = (GregorianCalendar) Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, increaseNum);
return c.getTime();
}


/**
* 得到一周中星期几的日期

* @param date
* @param day
* @return
*/
public static Date getDayOfWeek(Date date, int day) {
GregorianCalendar c = (GregorianCalendar) Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, day);
return c.getTime();
}


/**
* 把yyyy-MM-dd类型的日期字符串转换成yyyy-MM-dd 00:00:00或者yyyy-MM-dd 23:59:59类型字符串

* @param reqMap
*            请求的map其中包含beginTime,endTime此类字段
* @param startTimeKey
*            开始时间存在reqMap中的key值
* @param endTimeKey
*            结束时间存在reqMap中的key值
* @return
*/
public static Map setDayToTime(Map reqMap, String startTimeKey, String endTimeKey) {
if (!StringUtil.isEmpty(startTimeKey) && !StringUtil.isEmpty((String) reqMap.get(startTimeKey))) {
String startDate = (String) reqMap.get(startTimeKey);
startDate = fmtDate(getDate(startDate, "yyyy-MM-dd"), "yyyy-MM-dd");
reqMap.put(startTimeKey, startDate + " 00:00:00");
}
if (!StringUtil.isEmpty(endTimeKey) && !StringUtil.isEmpty((String) reqMap.get(endTimeKey))) {
String endDate = (String) reqMap.get(endTimeKey);
endDate = fmtDate(getDate(endDate, "yyyy-MM-dd"), "yyyy-MM-dd");
reqMap.put(endTimeKey, endDate + " 23:59:59");
}
return reqMap;
}


/**
* 把yyyy-MM-dd类型的日期字符串转换成yyyy-MM-dd 00:00:00或者yyyy-MM-dd 23:59:59类型字符串

* @param reqMap
*            请求的map其中包含beginTime,endTime此类字段
* @param startTimeKey
*            开始时间存在reqMap中的key值
* @param endTimeKey
*            结束时间存在reqMap中的key值
* @return
*/
public static Map setDayToTimeWithDefault(Map reqMap, String startTimeKey, String endTimeKey) {
String startTime = (String) reqMap.get(startTimeKey);
String endTime = (String) reqMap.get(endTimeKey);
if (StringUtil.isEmpty(startTime)) {
reqMap.put(startTimeKey, getMonthFirstDay(new Date()));
}
if (StringUtil.isEmpty(endTime)) {
reqMap.put(endTimeKey, getMonthLastDay(new Date()));
}
return setDayToTime(reqMap, startTimeKey, endTimeKey);
}


/**
* 比较两个时间的时差

* @param DATE1
* @param DATE2
* @return
*/


public static long timeDifference(String DATE1, String DATE2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long days = 0;
try {
Date d1 = df.parse(DATE1);
Date d2 = df.parse(DATE2);
long diff = d2.getTime() - d1.getTime();
days = diff / (1000 * 60 * 60 * 24);
} catch (Exception e) {
}
return days;
}
/**
* 比较时间大小

* @param DATE1
* @param DATE2
* @return
*/
public static int compare_date(String DATE1, String DATE2) {


DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() > dt2.getTime()) {
return -1;
} else if (dt1.getTime() < dt2.getTime()) {
return 1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
public static void main(String[] args) {
Date date = new Date();
// fmtDate(date, "yyyy-MM-dd hh:mm:ss");
String nowTime = DateUtil.fmtDate(date, "yyyy-MM-dd HH:mm:ss");
String lastDay = DateUtil.fmtDate(DateUtil.getLastDayDate(date), "yyyy-MM-dd");
int ints = compare_date(nowTime, lastDay + " 23:30:00");
System.out.println(ints);
}


}


2 js


/** ******************************js时间工具**************************************** */
DateUtil = {};

DateUtil.isLeapYear = function(date) {
	return (0 == date.getYear() % 4 && ((date.getYear() % 100 != 0) || (date.getYear() % 400 == 0)));
};

/**
 * 格式化日期
 */
DateUtil.fomatDate = function(date, fmt) {
	var yyyy = date.getFullYear();
	var MM = date.getMonth();
	var dd = date.getDate();
	var HH = date.getHours();
	var mm = date.getMinutes();
	var ss = date.getSeconds();
	var hh = HH > 12 ? HH - 12 : HH;
	var dateStr = fmt.replace('yyyy', yyyy).replace('MM',DateUtil.addZero(MM + 1)).replace('dd', DateUtil.addZero(dd))
			.replace('HH', DateUtil.addZero(HH)).replace('mm',DateUtil.addZero(mm)).replace('ss', DateUtil.addZero(ss))
			.replace('hh', DateUtil.addZero(hh));
	return dateStr;
};

DateUtil.addZero = function(num) {
	if (num < 10){
		return '0' + num;
	}
	return num;
};

/**
 * 将日期字符串转成日期 fmt:yyyy-MM-dd HH:mm:ss 或 yyyy-MM-dd
 */
DateUtil.parseDate = function(str, fmt) {
	if (!str) {
		return null;
	}
	var date;
	var year = 0;
	var month = 0;
	var day = 0;
	var hour = 0;
	var minute = 0;
	var second = 0;
	var tempStrs = str.split(' ');
	if (tempStrs[0]) {
		var dateStrs = tempStrs[0].split("-");
		year = parseInt(dateStrs[0], 10);
		month = parseInt(dateStrs[1], 10) - 1;
		day = parseInt(dateStrs[2], 10);
	}
	if (tempStrs[1]) {
		var timeStrs = tempStrs[1].split(":");
		hour = parseInt(timeStrs[0], 10);
		minute = parseInt(timeStrs[1], 10);
		second = parseInt(timeStrs[2], 10);
	}

	if (fmt == 'yyyy-MM-dd') {
		date = new Date(year, month, day);
		return date;
	} else if (fmt == 'yyyy-MM-dd HH:mm:ss') {
		date = new Date(year, month, day, hour, minute, second);
		return date;
	}
	return null;
};
/**
 * 获取指定日期最后一天日期
 */
DateUtil.getLastDate = function(date) {
	date = arguments[0] || new Date();
	var newDate = new Date(date.getTime());
	newDate.setMonth(newDate.getMonth() + 1);
	newDate.setDate(1);
	var time = newDate.getTime() - 24 * 60 * 60 * 1000;
	newDate = new Date(time);
	return newDate;
};
/**
 * 获取指定日期第一天日期
 */
DateUtil.getFirstDate = function(date) {
	date = arguments[0] || new Date();
	var newDate = new Date(date.getTime());
	newDate.setDate(1);
	return newDate;
};
/**
 * 获取周的第一天
 */
DateUtil.getWeekStartDate = function(date){
	date = arguments[0] || new Date();
    return new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay()+1);  
}   
/**
 * 获取周的最后一天
 */
DateUtil.getWeekEndDate = function(date){
	date = arguments[0] || new Date();
    return new Date(date.getFullYear(), date.getMonth(), date.getDate() + (6-date.getDay()+1));  
}  
/**
 * 获取日期差
 */
DateUtil.getDateDiff = function(start,end) {
	return Math.round(Math.abs(start - end )/(1000*60*60*24));
};
/**
 * 日期计算
 * 
 * @param strInterval
 *            string 可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
 * @param num
 *            int
 * @param date
 *            Date 日期对象
 * @return Date 返回日期对象
 */
DateUtil.dateAdd = function(strInterval, num, date) {
	date = arguments[2] || new Date();
	switch (strInterval) {
	case 's':
		return new Date(date.getTime() + (1000 * num));
	case 'n':
		return new Date(date.getTime() + (60000 * num));
	case 'h':
		return new Date(date.getTime() + (3600000 * num));
	case 'd':
		return new Date(date.getTime() + (86400000 * num));
	case 'w':
		return new Date(date.getTime() + ((86400000 * 7) * num));
	case 'm':
		return new Date(date.getFullYear(), (date.getMonth()) + num, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
	case 'y':
		return new Date((date.getFullYear() + num), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
	}
};

你可能感兴趣的:(java)