Java Date 日期 时间 相关方法
DateTools.java
import java.text.SimpleDateFormat; import java.util.Date; /*** 日期操作類*/ public class DateTools {/**yyyyMMddHHmmss* * @return*/public static String getAllDate(){SimpleDateFormat lFormat; //格式可以自己根據(jù)需要修改 lFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String gRtnStr = lFormat.format(new Date()); return gRtnStr;}/*** 獲得yymmdd類型的日期* @param date* @return*/public static String getDateString(Date date){String year =(date.getYear()+1900)+"";String mm = (date.getMonth()+1)+"";if(Integer.valueOf(mm).intValue()<10){mm="0"+mm;}String day = date.getDate()+"";if(Integer.valueOf(day).intValue()<10)day="0"+day;return year+mm+day;}/*** 獲得yymmdd類型的日期(日期的前1天)* @param date* @return*/public static String getZDateString(Date date){date.setDate(date.getDate()-1);String year =(date.getYear()+1900)+"";String mm = (date.getMonth()+1)+"";if(Integer.valueOf(mm).intValue()<10){mm="0"+mm;}String day = date.getDate()+"";if(day.length()==1)day="0"+day;return year+mm+day;}/*** 獲得yy-mm-dd類型的日期* @param date* @return*/public static String DateString(Date date){String year =(date.getYear()+1900)+"";String mm = (date.getMonth()+1)+"";if(Integer.valueOf(mm).intValue()<10){mm="0"+mm;}String day = date.getDate()+"";if(day.length()==1){day="0"+day;}return year+"-"+mm+"-"+day;}//得到當(dāng)前時間public static String getCurrentDateTime() {java.text.SimpleDateFormat d = new java.text.SimpleDateFormat();d.applyPattern("HH:mm:ss");java.util.Date nowdate = new java.util.Date();String str_date = d.format(nowdate);return str_date;}/*** 時間格式化* @return*/public static String getTimeString(String time){String[] ti = time.split(":");if(ti[1].length()==1){time = ti[0]+"0"+ti[1];}else{time = ti[0]+ti[1];}return time;}public static String TimeString(){Date date = new Date();return getTimeString(date.getHours()+":"+date.getMinutes());}public static void main(String args[]){System.out.println(DateTools.getZDateString(new Date()));} }DateTime.java
import java.util.*; import java.text.*;public class DateTime {public DateTime() {}public static final long SECOND = 1000;public static final long MINUTE = 60 * SECOND;public static final long HOUR = 60 * MINUTE;public static final long DAY = 24 * HOUR;public static final long WEEK = 7 * DAY;public static final String SHORTFORMAT = "yyyy-MM-dd";public static final String SHORTFORMATNOSPIT = "yyyyMMdd";public static final String YEARMONTHFORMAT = "yyyy-MM";public static final String LONGFORMAT = "yyyy-MM-dd HH:mm:ss";/*** 獲得yymmdd類型的日期* @param date* @return*/public static String getDateString(Date date){String year =(date.getYear()+1900)+"";String mm = (date.getMonth()+1)+"";if(Integer.valueOf(mm).intValue()<10){mm="0"+mm;}String day = date.getDate()+"";return year+mm+day;}/*** 獲得yy-mm-dd類型的日期* @param date* @return*/public static String DateString(Date date){String year =(date.getYear()+1900)+"";String mm = (date.getMonth()+1)+"";if(Integer.valueOf(mm).intValue()<10){mm="0"+mm;}String day = date.getDate()+"";if(day.length()==1){day="0"+day;}return year+"-"+mm+"-"+day;}// 得到某一天是星期幾public static int getDateInWeek(String strDate) {DateFormat df = DateFormat.getDateInstance();try {df.parse(strDate);java.util.Calendar c = df.getCalendar();int day = c.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY;return day;} catch (ParseException e) {return -1;}}//得到當(dāng)前日期public static String getCurrentDate() {java.text.SimpleDateFormat d = new java.text.SimpleDateFormat();d.applyPattern("yyyy-MM-dd");java.util.Date nowdate = new java.util.Date();String str_date = d.format(nowdate);return str_date;}//得到當(dāng)前日期時間public static String getCurrentDateTime() {java.text.SimpleDateFormat d = new java.text.SimpleDateFormat();d.applyPattern("yyyy-MM-dd HH:mm:ss");java.util.Date nowdate = new java.util.Date();String str_date = d.format(nowdate);return str_date;}//根據(jù)日期獲得日期時間public static String getDateTime(java.util.Date date) {java.text.SimpleDateFormat d = new java.text.SimpleDateFormat();d.applyPattern("yyyy-MM-dd HH:mm:ss");String str_date = d.format(date);return str_date;}//獲得某月的最后一天public static int getDayNum(int year, int month) {if (month == 2) {return year % 400 != 0 && (year % 4 != 0 || year % 100 == 0) ? 28: 29;}String SmallMonth = ",4,6,9,11,";return SmallMonth.indexOf(String.valueOf(String.valueOf((new StringBuffer(",")).append(String.valueOf(month)).append(",")))) < 0 ? 31 : 30;}//返回兩個日期之間隔了多少天public static int DateDiff(Date date1, Date date2) {int i = (int) ( (date1.getTime() - date2.getTime()) / 3600 / 24 / 1000);return i;}//從放有日期的字符串中得到,相應(yīng)的年,月,日 style is "Y"or"y" 返回年 style is "M"or"m" 返回月 style//is "D"or"d" 返回日 日期字符串要求 "YYYY-MM-DD"public static int getYearMonthDate(String strDate, String style) {int year;int month;int day;int firstDash;int secondDash;if (strDate == null) {return 0;}firstDash = strDate.indexOf('-');secondDash = strDate.indexOf('-', firstDash + 1);if ((firstDash > 0) & (secondDash > 0)& (secondDash < strDate.length() - 1)) {year = Integer.parseInt(strDate.substring(0, firstDash));month = Integer.parseInt(strDate.substring(firstDash + 1,secondDash));day = Integer.parseInt(strDate.substring(secondDash + 1));} else {return 0;}if (style.equalsIgnoreCase("Y")) {return year;} else if (style.equalsIgnoreCase("M")) {return month;} else if (style.equalsIgnoreCase("D")) {return day;} else {return 0;}}// 某一天,過幾天后是幾號public static java.sql.Date DateAdd(java.sql.Date date, int addday) {java.sql.Date datenew = null;int year = DateTime.getYearMonthDate(date.toString(), "Y");int month = DateTime.getYearMonthDate(date.toString(), "M");int day = DateTime.getYearMonthDate(date.toString(), "D");day = day + addday;String dayStr = Integer.toString(year) + "-" + Integer.toString(month) +"-" + Integer.toString(day);datenew = datenew.valueOf(dayStr);//datenew.setTime(datenew.getTime()+day*3600*24*1000);//有問題。 改return datenew;}//某一天的前幾天是幾號public static java.sql.Date DateBefore(java.sql.Date date, int addday) {java.sql.Date datenew = null;int year = DateTime.getYearMonthDate(date.toString(), "Y");int month = DateTime.getYearMonthDate(date.toString(), "M");int day = DateTime.getYearMonthDate(date.toString(), "D");day = day - addday;String dayStr = Integer.toString(year) + "-" + Integer.toString(month)+ "-" + Integer.toString(day);datenew = datenew.valueOf(dayStr);// datenew.setTime(datenew.getTime()+day*3600*24*1000);// 有問題。 改return datenew;}//某一天是否是年的頭一天public static boolean isYearFirstDay(java.sql.Date date) {boolean i = false;if ((DateTime.getYearMonthDate(date.toString(), "M") == 1)&& (DateTime.getYearMonthDate(date.toString(), "D") == 1)) {i = true;}return i;}// 某一天是否是半年的頭一天public static boolean isHalfYearFirstDay(java.sql.Date date) {boolean i = false;if (((DateTime.getYearMonthDate(date.toString(), "M") == 1) && (DateTime.getYearMonthDate(date.toString(), "D") == 1))|| ((DateTime.getYearMonthDate(date.toString(), "M") == 7) && (DateTime.getYearMonthDate(date.toString(), "D") == 1))) {i = true;}return i;}public static String getHalfYearFirstDay(java.sql.Date date) {String month = "01";if (DateTime.getYearMonthDate(date.toString(), "M") >= 7) {month = "07";}String day = Integer.toString(DateTime.getYearMonthDate(date.toString(), "Y"))+ "-" + month + "-01";return day;}// 某一天是否是半年的最后一天public static boolean isHalfYearLastDay(java.sql.Date date) {boolean i = false;if (((DateTime.getYearMonthDate(date.toString(), "M") == 12) && (DateTime.getYearMonthDate(date.toString(), "D") == 31))|| ((DateTime.getYearMonthDate(date.toString(), "M") == 6) && (DateTime.getYearMonthDate(date.toString(), "D") == 30))) {i = true;}return i;}public static String getHalfYearLastDay(java.sql.Date date) {String month = "-06-30";if (DateTime.getYearMonthDate(date.toString(), "M") >= 7) {month = "-12-31";}String day = Integer.toString(getYearMonthDate(date.toString(), "Y"))+ "-" + month;return day;}// 某一天是否是年的最后一天public static boolean isYearLastDay(java.sql.Date date) {boolean i = false;if ((DateTime.getYearMonthDate(date.toString(), "M") == 12)&& (DateTime.getYearMonthDate(date.toString(), "D") == 31)) {i = true;}return i;}//某一天是否是季的頭一天public static boolean isQuarterFirstDay(java.sql.Date date) {boolean i = false;if (((DateTime.getYearMonthDate(date.toString(), "M") == 1)|| (DateTime.getYearMonthDate(date.toString(), "M") == 4)|| (DateTime.getYearMonthDate(date.toString(), "M") == 7) || (DateTime.getYearMonthDate(date.toString(), "M") == 10))&& (DateTime.getYearMonthDate(date.toString(), "D") == 1)) {i = true;}return i;}public static String getQuarterFirstDay(java.sql.Date date) {String month = "01";if (DateTime.getYearMonthDate(date.toString(), "M") >= 10) {month = "10";} else if (DateTime.getYearMonthDate(date.toString(), "M") >= 7) {month = "07";} else if (DateTime.getYearMonthDate(date.toString(), "M") >= 4) {month = "04";} else if (DateTime.getYearMonthDate(date.toString(), "M") >= 1) {month = "01";}String day = Integer.toString(DateTime.getYearMonthDate(date.toString(), "Y"))+ "-" + month + "-01";return day;}//某一天是否是季的最后一天public static boolean isQuarterLastDay(java.sql.Date date) {boolean i = false;if ((DateTime.getYearMonthDate(date.toString(), "M") == 3)&& (DateTime.getYearMonthDate(date.toString(), "D") == 31)) {i = true;}if ((DateTime.getYearMonthDate(date.toString(), "M") == 6)&& (DateTime.getYearMonthDate(date.toString(), "D") == 30)) {i = true;}if ((DateTime.getYearMonthDate(date.toString(), "M") == 9)&& (DateTime.getYearMonthDate(date.toString(), "D") == 30)) {i = true;}if ((DateTime.getYearMonthDate(date.toString(), "M") == 12)&& (DateTime.getYearMonthDate(date.toString(), "D") == 31)) {i = true;}return i;}public static String getQuarterLastDay(java.sql.Date date) {String month = "-01-31";if (DateTime.getYearMonthDate(date.toString(), "M") >= 10) {month = "-12-31";} else if (DateTime.getYearMonthDate(date.toString(), "M") >= 7) {month = "-09-30";} else if (DateTime.getYearMonthDate(date.toString(), "M") >= 4) {month = "-06-30";}String day = Integer.toString(DateTime.getYearMonthDate(date.toString(), "Y"))+ "-" + month;return day;}//某一天是否是月的最后一天public static boolean isMonthLastDay(java.sql.Date date) {boolean i = false;java.sql.Date des_date = null;String month;String str_date = date.toString();String year = str_date.substring(0, str_date.indexOf("-"));int m = new Integer(str_date.substring(str_date.indexOf("-") + 1,str_date.lastIndexOf("-"))).intValue() + 1;month = new Integer(m).toString();if (m < 10) {month = "0" + month;}java.sql.Date mid_date = null;mid_date = mid_date.valueOf(year + "-" + month + "-01");des_date = DateTime.DateAdd(mid_date, -1);if (DateTime.DateDiff(des_date, date) == 0) {i = true;}return i;}//某一天是否是月的第一天public static boolean isMonthFisrtDay(java.sql.Date date) {boolean i = false;if ((DateTime.getYearMonthDate(date.toString(), "D") == 1)) {i = true;}return i;}//獲得月的第一天public static String getMonthFisrtDay(java.sql.Date date){String month;if (DateTime.getYearMonthDate(date.toString(), "M") > 9) {month = Integer.toString(DateTime.getYearMonthDate(date.toString(), "M"));} else {month = "0"+ Integer.toString(DateTime.getYearMonthDate(date.toString(), "M"));}String day = Integer.toString(DateTime.getYearMonthDate(date.toString(), "Y"))+ "-" + month + "-01";return day;}public static java.sql.Timestamp getTimestamp() {try {java.text.SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");java.util.Calendar calendar = java.util.Calendar.getInstance();String mystrdate = myFormat.format(calendar.getTime());return java.sql.Timestamp.valueOf(mystrdate);} catch (Exception e) {return null;}}public static java.sql.Timestamp getTimestamp(String datestr) {try {java.text.SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String mystrdate = myFormat.format(myFormat.parse(datestr));return java.sql.Timestamp.valueOf(mystrdate);} catch (Exception e) {return null;}}//格式化日期(Y-年,M-月,D-日 HH:mm:ss 小時:分鐘:秒)public static String getDate(java.util.Date date, String format) {String result = null;try {java.text.SimpleDateFormat myFormat = new SimpleDateFormat(format);result = myFormat.format(date);} catch (Exception e) {return null;}return result;}public static String getDate(java.util.Date date) {return getDate(date, LONGFORMAT);}//轉(zhuǎn)換成時間戳public static java.sql.Timestamp getDate(String datestr) {try {java.text.SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");Date date = myFormat.parse(datestr);myFormat.applyLocalizedPattern("yyyy-MM-dd HH:mm:ss");String mystrdate = myFormat.format(date);return java.sql.Timestamp.valueOf(mystrdate);} catch (Exception e) {return null;}}//將日期格式化成yyyy-MM-dd形式public static java.util.Date format(String datestr) {try {java.text.SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");Date date = myFormat.parse(datestr);return date;} catch (Exception e) {return new Date(datestr);}}//格式化日期(Y-年,M-月,D-日 HH:mm:ss 小時:分鐘:秒)public static java.util.Date format(String datestr, String format) {try {java.text.SimpleDateFormat myFormat = new SimpleDateFormat(format);Date date = myFormat.parse(datestr);return date;} catch (Exception e) {return null;}}//獲得數(shù)據(jù)庫格式的日期public static java.sql.Date getSqlDate(java.util.Date date) {java.sql.Date result = null;try {java.text.SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");String mystrdate = myFormat.format(date);result = java.sql.Date.valueOf(mystrdate);} catch (Exception e) {return null;}return result;}public static java.util.Date addMonth(java.util.Date date, int month) {String strdate = getDate(date, SHORTFORMAT);int curmonth = Integer.parseInt(strdate.substring(5, 7));int year = Integer.parseInt(strdate.substring(0, 4));int addyear = month / 12;year = year + addyear;curmonth = curmonth + (month % 12);if (curmonth > 12) {curmonth = 1;year = year + 1;}String strmonth = String.valueOf(curmonth);if (strmonth.length() == 1) {strmonth = "0" + strmonth;}strdate = String.valueOf(year) + "-" + strmonth + "-"+ strdate.substring(8, 10);return format(strdate, SHORTFORMAT);}/*** 傳遞日期, 獲得上個月的最后1天* @param dt* @return*/public static String getUpMDate(Date dt){dt.setDate(1);dt.setDate(dt.getDate()-1);return dt.toLocaleString();}/***得到當(dāng)前是那一天。**/public static String getDate() {java.text.SimpleDateFormat d = new java.text.SimpleDateFormat();d.applyPattern("yyyy-MM-dd");java.util.Date nowdate = new java.util.Date();String str_date = d.format(nowdate);return str_date;}/*** 將10位日期格式化為8位* @param dt* @return*/public static String getShortDate(String dt){if(dt != null){java.text.SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");try {Date date = myFormat.parse(dt);return getDate(date,SHORTFORMATNOSPIT);} catch (ParseException e) {return dt;}}elsereturn dt;}/*** 將8位日期格式化為10位* @param dt* @return*/public static String getLongDate(String dt){if(dt != null){java.text.SimpleDateFormat myFormat = new SimpleDateFormat("yyyyMMdd");try {Date date = myFormat.parse(dt);return getDate(date,SHORTFORMAT);} catch (ParseException e) {return dt;}}elsereturn dt;}/*** 判斷是否是當(dāng)月* @param month* @return*/public static boolean isSameYearMonth(String date){try{String currdate = getCurrentDate();currdate = getShortDate(currdate).substring(0,6);String lastdate = getShortDate(date).substring(0,6);if(lastdate.equals(currdate)){return true;}else{return false;}}catch(NumberFormatException e){return false;}}public static void main(String[] args){Date d = new Date("20070829");Date f = new Date("20070912");System.out.println(d.getDate()-f.getDate());} }?
???這幾天一直在處理Java的日期問題,通常需要按要求生成日期的話,通常會用到util包中的Calendar類,再用Calendar的getTime()方法生成對應(yīng)的Date,最后用SimpleDateFormat輸出。
?
1.?獲取當(dāng)期日期、年份、月份
import?java.util.Calendar;
public?class?Main?{
??public?static?void?main(String[]?args)?{
????Calendar?now?=?Calendar.getInstance();
????System.out.println("Current?Year?is?:?"?+?now.get(Calendar.YEAR));
????//?month?start?from?0?to?11
????System.out.println("Current?Month?is?:?"?+?(now.get(Calendar.MONTH)?+?1));
????System.out.println("Current?Date?is?:?"?+?now.get(Calendar.DATE));
??}
}
?
2.?獲取前一天、前一個月的日期
Calendar?calendar?=?Calendar.getInstance();//此時打印它獲取的是系統(tǒng)當(dāng)前時間
????????calendar.add(Calendar.DATE,?-1);????//得到前一天
String ?yestedayDate
= new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
????????calendar.add(Calendar.MONTH,?-1);????//得到前一個月
????????int?year?=?calendar.get(Calendar.YEAR);
???????int?month?=?calendar.get(Calendar.MONTH)+1;?//輸出前一月的時候要記得加1
?
3.?字符串轉(zhuǎn)為日期格式
String date =?"2010-02-01 23:59:59";
SimpleDateFormat sf =?new?SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try?{
Date d = sf.parse(date);
System.out.println(sf.format(d));
}?catch?(ParseException e) {
e.printStackTrace();
}
總結(jié)
以上是生活随笔為你收集整理的Java Date 日期 时间 相关方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简单的REST的框架实现
- 下一篇: cocos2d-x中几种存储数据的方式