日期操作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<String, Object> setDayToTime(Map<String, Object> 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<String, Object> setDayToTimeWithDefault(Map<String, Object> 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());
	}
};

發佈了85 篇原創文章 · 獲贊 16 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章