1. 程式人生 > 其它 >自定義 java 日期、時間 處理函式集

自定義 java 日期、時間 處理函式集

廢話少說,在shell下很容易:

june@deepin :~> date -d@1353027149 2012年 11月 16日 星期五 08:52:29 CST june@deepin :~>

但是 java 下比較折騰,網上轉來抄去的程式碼也都是錯誤一大堆。。。

java程式碼如下:

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

public class MyDateUtil {

	public static String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; // 注意 HH 和 hh 的區別!
	public static String DATE_FORMAT = "yyyyMMdd";

	// 計算起始日期間隔多少天
	public static String getDayInterval(String st, String ed) {
		SimpleDateFormat myFormatter = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		long day = 0;
		try {
			java.util.Date startDate = myFormatter.parse(st);
			java.util.Date endDate = myFormatter.parse(ed);
			day = (endDate.getTime() - startDate.getTime())
					/ (24 * 60 * 60 * 1000);
		} catch (Exception e) {
			return "";
		}
		return day + "";
	}

	// 判斷起始時間差是否在多少分鐘內
	public static boolean getMinitueInterval(String st, String ed, int mins) {
		SimpleDateFormat myFormatter = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		boolean inMins = false;
		try {
			java.util.Date startDate = myFormatter.parse(st);
			java.util.Date endDate = myFormatter.parse(ed);
			double minitue = (endDate.getTime() * 1.0 - startDate.getTime())
					/ (60 * 1000);
			System.out.println(minitue);
			if (minitue >= 0 && minitue <= mins) {
				inMins = true;
			} else {
				inMins = false;
			}

		} catch (Exception e) {
			inMins = false;
		}
		return inMins;
	}

	// 指定日期 N 天以前的日期
	public static String getNDaysAgo(String date, int nDaysAgo) {
		Calendar cal1 = Calendar.getInstance();
		Date dateFormat = null;
		try {
			dateFormat = new SimpleDateFormat(DATE_FORMAT).parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Long dateLong = dateFormat.getTime(); // 得到的是 long,類似 date
												// -d"2012-11-12 12:00:00" +%s
		cal1.setTime(new java.util.Date(dateLong));
		cal1.add(Calendar.DATE, -nDaysAgo);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		return formatter.format(cal1.getTime());
	}

	// 得到起始範圍內的日期列表,包含起始日期,可設定間隔天數
	public static List<String> getDateList(String startDate, String endDate,
			int intervalDay) {
		List<String> listDate = new ArrayList<String>();

		SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
		Date dBegin;
		Date dEnd;
		try {
			dBegin = f.parse(startDate);
			dEnd = f.parse(endDate);
			if (dBegin.getTime() <= dEnd.getTime()) {
				for (long i = dBegin.getTime(); i <= dEnd.getTime(); i += 86400000 * (intervalDay + 1)) {
					Date d = new Date(i);
					String date = f.format(d);
					// System.out.println(date);
					listDate.add(date);
				}
			} else {
				for (long i = dBegin.getTime(); i >= dEnd.getTime(); i -= 86400000 * (intervalDay + 1)) {
					Date d = new Date(i);
					String date = f.format(d);
					// System.out.println(date);
					listDate.add(date);
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return listDate;
	}

	// 獲取指定日期的前一週(1~7天)時間
	public static List<String> getWeekList(String startDate) {
		List<String> listDate = new ArrayList<String>();

		SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
		Date dBegin;
		try {
			dBegin = f.parse(startDate);
			for (long i = 1; i <= 7; i++) {
				Date d = new Date(dBegin.getTime() - 86400000 * i);
				String date = f.format(d);
				// System.out.println(date);
				listDate.add(date);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return listDate;
	}

	// 將長整型字串轉換為日期字串,注意:不能帶毫秒
	public static String millis2Time(String longStr) {
		long seconds = Long.parseLong(longStr);
		long millis = seconds * 1000;
		Date date = new Date(millis);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
				Locale.CHINA);
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		String formattedDate = sdf.format(date);
		return formattedDate;
	}

	// 將日期字串轉換為長整型數字,注意:輸出不帶毫秒
	public static long time2Millis(String date) {
		Date dateFormat = null;
		try {
			dateFormat = new SimpleDateFormat(TIME_FORMAT).parse(date);
		} catch (ParseException e) {
			System.out.println(e.toString());
		}
		Long dateLong = dateFormat.getTime(); // 得到的是 long,類似 date
												// -d"2012-11-12 12:00:00" +%s
		return dateLong;
	}

	// 得到指定日期的星期數,注意:1=星期日 2=星期一 7=星期六,其他類推
	public static String getWeek(String sdate) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(sdate, pos);
		// Date date = strToDate(sdate);
		Calendar c = Calendar.getInstance();
		c.setTime(strtodate);
		// int hour=c.get(Calendar.DAY_OF_WEEK);
		// hour中存的就是星期幾了,其範圍 1~7
		// 1=星期日 2=星期一 7=星期六,其他類推
		// return new SimpleDateFormat("E").format(c.getTime()); // 返回 星期一
		return String.valueOf(c.get(Calendar.DAY_OF_WEEK));
	}

	// 得到 1 年以前的日期
	public static String getOneYearsAgo(String dateStr) {
		SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
		Calendar cal = Calendar.getInstance();
		try {
			cal.setTime(f.parse(dateStr));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		cal.add(Calendar.YEAR, -1);
		Date oneYearsAgo = cal.getTime();
		return f.format(oneYearsAgo);
	}

	// 得到 N 個月以前的日期
	public static String getNMonthsAgo(String dateStr, int n) {
		SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
		Calendar cal = Calendar.getInstance();
		try {
			cal.setTime(f.parse(dateStr));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		cal.add(Calendar.MONTH, n);
		Date nMonthsAgo = cal.getTime();
		return f.format(nMonthsAgo);
	}

	// 獲得上月最後一天的日期
	public static String getPreMonthEnd(String dateStr) {
		String str = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Calendar lastDate = Calendar.getInstance();
		try {
			lastDate.setTime(sdf.parse(dateStr));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		lastDate.add(Calendar.MONTH, -1);// 減一個月
		lastDate.set(Calendar.DATE, 1);// 把日期設定為當月第一天
		lastDate.roll(Calendar.DATE, -1);// 日期回滾一天,也就是本月最後一天
		str = sdf.format(lastDate.getTime());
		return str;
	}

	// 獲得上月最第一天的日期
	public static String getPreMonthFirst(String dateStr) {
		String str = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Calendar lastDate = Calendar.getInstance();
		try {
			lastDate.setTime(sdf.parse(dateStr));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		lastDate.set(Calendar.DATE, 1);// 設為當前月的1號
		lastDate.add(Calendar.MONTH, -1);// 減一個月,變為下月的1號
		str = sdf.format(lastDate.getTime());
		return str;
	}

	public static void main(String[] args) {

		// List<String> dateList = getDateList("20130108", "20130107", 0);
		// for (String date : dateList) {
		// System.out.println(date);
		// }

		// List<String> dateList = getWeekList("20121112");
		// for(String date : dateList){
		// System.out.println(date);
		// }

		// System.out.println(millis2Time("1318521600"));

		// System.out.println(time2Millis("2012-12-16 00:05:13")/1000/60);

		// System.out.println(getNDaysAgo("20130114", 1));
		// System.out.println(getNDaysAgo("20130114", 7));

		System.out.println(getWeek("20130122"));

		// System.out.println(getOneYearsAgo("20120227"));

		// System.out.println(getNMonthsAgo("20110827", -6));
		// System.out.println(getNMonthsAgo("20110829", -6));
		// System.out.println(getNMonthsAgo("20120229", -12));

		// System.out.println("20110827".substring(6, 8));

		// System.out.println(getPreMonthFirst("20130430"));

		// System.out.println(getMinitueInterval("2012-12-16 00:05:13",
		// "2012-12-16 00:10:13", 5));
	}
}

結果:

2012-11-16 08:52:29

___________________________________________________

PS:

關於 SimpleDateFormat 的非執行緒安全問題及其解決方案

http://my.oschina.net/leejun2005/blog/152253#OSC_h4_7

JAVA獲取各種各樣的時間、時間對比 方法彙總

http://hechuanzhen.iteye.com/blog/1736740

用於處理java當中各種使用到日期的方法

http://lushuifa.iteye.com/blog/1781819

Java日期計算之Joda-Time

http://rensanning.iteye.com/blog/1546652

http://persevere.iteye.com/blog/1755237