您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“java時(shí)間日期使用與查詢的示例分析”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“java時(shí)間日期使用與查詢的示例分析”這篇文章吧。
只要格式正確,直接比較字符串就可以了呀,精確到秒的也一樣
String s1 = "2003-12-12 11:30:24"; String s2 = "2004-04-01 13:31:40"; int res = s1.compareTo(s2);
求日期差
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date begin=df.parse("2004-01-02 11:30:24"); Date end = df.parse("2004-03-26 13:31:40"); long between=(end.getTime()-begin.getTime())/1000;//除以1000是為了轉(zhuǎn)換成秒 int day=between/(24*3600); int hour=between%(24*3600)/3600; int minute=between%3600/60; int second=between%60;
經(jīng)常用到時(shí)間日期類,所以就將常用的日期方法和屬性都?xì)w納總結(jié)如下,方便大家查找
1.計(jì)算某一月份的最大天數(shù)
Calendar time=Calendar.getInstance(); time.clear(); time.set(Calendar.YEAR,year); time.set(Calendar.MONTH,i-1);//注意,Calendar對象默認(rèn)一月為0 int day=time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天數(shù)
注:在使用set方法之前,最好先clear一下,否則很多信息會(huì)繼承自系統(tǒng)當(dāng)前時(shí)間
2.Calendar和Date的轉(zhuǎn)化
(1) Calendar轉(zhuǎn)化為Date
Calendar cal=Calendar.getInstance(); Date date=cal.getTime();
(2) Date轉(zhuǎn)化為Calendar
Date date=new Date(); Calendar cal=Calendar.getInstance(); cal.setTime(date);
3.格式化輸出日期時(shí)間
Date date=new Date(); SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println(df.format(date));
4.計(jì)算一年中的第幾星期
(1)計(jì)算某一天是一年中的第幾星期
Calendar cal=Calendar.getInstance(); cal.set(Calendar.YEAR, 2006); cal.set(Calendar.MONTH, 9); cal.set(Calendar.DAY_OF_MONTH, 3); int weekno=cal.get(Calendar.WEEK_OF_YEAR);
(2)計(jì)算一年中的第幾星期是幾號
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); Calendar cal=Calendar.getInstance(); cal.set(Calendar.YEAR, 2006); cal.set(Calendar.WEEK_OF_YEAR, 1); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); System.out.println(df.format(cal.getTime()));
輸出:
2006-01-02
5.add()和roll()的用法
(1)add()方法
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); Calendar cal=Calendar.getInstance(); cal.set(Calendar.YEAR, 2006); cal.set(Calendar.MONTH, 9); cal.set(Calendar.DAY_OF_MONTH, 3); cal.add(Calendar.DATE, -4); Date date=cal.getTime(); System.out.println(df.format(date)); cal.add(Calendar.DATE, 4); date=cal.getTime(); System.out.println(df.format(date));
輸出:
2006-08-30
2006-10-03
(2)roll方法
cal.set(Calendar.YEAR, 2006); cal.set(Calendar.MONTH, 9); cal.set(Calendar.DAY_OF_MONTH, 3); cal.roll(Calendar.DATE, -4); date=cal.getTime(); System.out.println(df.format(date)); cal.roll(Calendar.DATE, 4); date=cal.getTime(); System.out.println(df.format(date));
輸出:
2006-10-29
2006-10-03
可見,roll()方法在本月內(nèi)循環(huán),一般使用add()方法;
6.計(jì)算兩個(gè)任意時(shí)間中間的間隔天數(shù)
(1)傳進(jìn)Calendar對象
/** */ /**計(jì)算兩個(gè)時(shí)間之間相隔天數(shù) * @param startday 開始時(shí)間 * @param endday 結(jié)束時(shí)間 * @return */ public int getIntervalDays(Calendar startday,Calendar endday)...{ //確保startday在endday之前 if(startday.after(endday))...{ Calendar cal=startday; startday=endday; endday=cal; } //分別得到兩個(gè)時(shí)間的毫秒數(shù) long sl=startday.getTimeInMillis(); long el=endday.getTimeInMillis(); long ei=el-sl; //根據(jù)毫秒數(shù)計(jì)算間隔天數(shù) return (int)(ei/(1000*60*60*24)); }
(2)傳進(jìn)Date對象
/** */ /**計(jì)算兩個(gè)時(shí)間之間相隔天數(shù) * @param startday 開始時(shí)間 * @param endday 結(jié)束時(shí)間 * @return */ public int getIntervalDays(Date startday,Date endday)...{ //確保startday在endday之前 if(startday.after(endday))...{ Date cal=startday; startday=endday; endday=cal; } //分別得到兩個(gè)時(shí)間的毫秒數(shù) long sl=startday.getTime(); long el=endday.getTime(); long ei=el-sl; //根據(jù)毫秒數(shù)計(jì)算間隔天數(shù) return (int)(ei/(1000*60*60*24)); }
同理,可以用相同的方法計(jì)算出任意兩個(gè)時(shí)間相隔的小時(shí)數(shù),分鐘數(shù),秒鐘數(shù)等
注:以上方法是完全按時(shí)間計(jì)算,有時(shí)并不能令人滿意,如:
startday="2006-10-11 20:00:00" endday="2006-10-12 8:00:00"
計(jì)算結(jié)果為0,但是我們也許相讓計(jì)算結(jié)果變?yōu)?,此時(shí)可以用如下方法實(shí)現(xiàn):
在傳參之前,先設(shè)定endday的時(shí)間,如:
endday.set(Calendar.HOUR_OF_DAY, 23); endday.set(Calendar.MINUTE, 59); endday.set(Calendar.SECOND, 59); endday.set(Calendar.MILLISECOND, 59);
這樣再傳進(jìn)去startday,endday,則結(jié)果就如我們所愿了。不過,如果嫌以上方法麻煩,可以參考以下方法:
(3)改進(jìn)精確計(jì)算相隔天數(shù)的方法
public int getDaysBetween (Calendar d1, Calendar d2) ...{ if (d1.after(d2)) ...{ // swap dates so that d1 is start and d2 is end java.util.Calendar swap = d1; d1 = d2; d2 = swap; } int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR); int y2 = d2.get(Calendar.YEAR); if (d1.get(Calendar.YEAR) != y2) ...{ d1 = (Calendar) d1.clone(); do ...{ days += d1.getActualMaximum(Calendar.DAY_OF_YEAR); //得到當(dāng)年的實(shí)際天數(shù) d1.add(Calendar.YEAR, 1); } while (d1.get(Calendar.YEAR) != y2); } return days; }
獲取系統(tǒng)當(dāng)前時(shí)間:
public static String getSystemTime(){ Date date=new Date(); SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return df.format(date); } //字符串轉(zhuǎn)化成時(shí)間類型(字符串可以是任意類型,只要和SimpleDateFormat中的格式一致即可) java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("M/dd/yyyy hh:mm:ss a",java.util.Locale.US); java.util.Date d = sdf.parse("5/13/2003 10:31:37 AM"); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String mDateTime1=formatter.format(d); //當(dāng)前時(shí)間 Calendar cal = Calendar.getInstance(); // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss G E D F w W a E F"); String mDateTime=formatter.format(cal.getTime()); //1年前日期 java.util.Date myDate=new java.util.Date(); long myTime=(myDate.getTime()/1000)-60*60*24*365; myDate.setTime(myTime*1000); String mDate=formatter.format(myDate); //明天日期 myDate=new java.util.Date(); myTime=(myDate.getTime()/1000)+60*60*24; myDate.setTime(myTime*1000); mDate=formatter.format(myDate); //兩個(gè)時(shí)間之間的天數(shù) SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date= myFormatter.parse("2003-05-1"); java.util.Date mydate= myFormatter.parse("1899-12-30"); long day=(date.getTime()-mydate.getTime())/(24*60*60*1000); //加半小時(shí) SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); java.util.Date date1 = format.parse("2002-02-28 23:16:00"); long Time=(date1.getTime()/1000)+60*30; date1.setTime(Time*1000); String mydate1=formatter.format(date1); //年月周求日期 SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM F E"); java.util.Date date2= formatter2.parse("2003-05 5 星期五"); SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd"); String mydate2=formatter3.format(date2); //求是星期幾 mydate= myFormatter.parse("2001-1-1"); SimpleDateFormat formatter4 = new SimpleDateFormat("E"); String mydate3=formatter4.format(mydate);
在開發(fā)web應(yīng)用中,針對不同的數(shù)據(jù)庫日期類型,我們需要在我們的程序中對日期類型做各種不同的轉(zhuǎn)換。若對應(yīng)數(shù)據(jù)庫數(shù)據(jù)是oracle的Date類型,即只需要年月日的,可以選擇使用java.sql.Date類型,若對應(yīng)的是MSsqlserver數(shù)據(jù)庫的DateTime類型,即需要年月日時(shí)分秒的,選擇java.sql.Timestamp類型
你可以使用dateFormat定義時(shí)間日期的格式,轉(zhuǎn)一個(gè)字符串即可
package personal.jessica; import java.util.Date; import java.util.Calendar; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Locale; class Datetest{ /** *method 將字符串類型的日期轉(zhuǎn)換為一個(gè)timestamp(時(shí)間戳記java.sql.Timestamp) *@param dateString 需要轉(zhuǎn)換為timestamp的字符串 *@return dataTime timestamp */ public final static java.sql.Timestamp string2Time(String dateString) throws java.text.ParseException { DateFormat dateFormat; dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.SSS", Locale.ENGLISH); //設(shè)定格式 //dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss", Locale.ENGLISH); dateFormat.setLenient(false); java.util.Date timeDate = dateFormat.parse(dateString); //util類型 java.sql.Timestamp dateTime = new java.sql.Timestamp(timeDate.getTime()); //Timestamp類型,timeDate.getTime()返回一個(gè)long型 return dateTime; } /** *method 將字符串類型的日期轉(zhuǎn)換為一個(gè)Date(java.sql.Date) *@param dateString 需要轉(zhuǎn)換為Date的字符串 *@return dataTime Date */ public final static java.sql.Date string2Date(String dateString) throws java.lang.Exception { DateFormat dateFormat; dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); dateFormat.setLenient(false); java.util.Date timeDate = dateFormat.parse(dateString); //util類型 java.sql.Date dateTime = new java.sql.Date(timeDate.getTime()); //sql類型 return dateTime; } public static void main(String[] args){ Date da = new Date(); //注意:這個(gè)地方da.getTime()得到的是一個(gè)long型的值 System.out.println(da.getTime()); //由日期date轉(zhuǎn)換為timestamp //第一種方法:使用new Timestamp(long) Timestamp t = new Timestamp(new Date().getTime()); System.out.println(t); //第二種方法:使用Timestamp(int year,int month,int date,int hour,int minute,int second,int nano) Timestamp tt = new Timestamp(Calendar.getInstance().get( Calendar.YEAR) - 1900, Calendar.getInstance().get( Calendar.MONTH), Calendar.getInstance().get( Calendar.DATE), Calendar.getInstance().get( Calendar.HOUR), Calendar.getInstance().get( Calendar.MINUTE), Calendar.getInstance().get( Calendar.SECOND), 0); System.out.println(tt); try { String sToDate = "2005-8-18"; //用于轉(zhuǎn)換成java.sql.Date的字符串 String sToTimestamp = "2005-8-18 14:21:12.123"; //用于轉(zhuǎn)換成java.sql.Timestamp的字符串 Date date1 = string2Date(sToDate); Timestamp date2 = string2Time(sToTimestamp); System.out.println("Date:"+date1.toString()); //結(jié)果顯示 System.out.println("Timestamp:"+date2.toString()); //結(jié)果顯示 } catch(Exception e) { e.printStackTrace(); } } }
下面是例子:
Java代碼
package test; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Hashtable; import javax.swing.JOptionPane; public class Test2{ public static Boolean isdate(String s){ String a[]=s.split("-"); Boolean flg=true; if(!(Integer.parseint(a[0])>=1950 && Integer.parseint(a[0])<=2050)){ flg=false; } return flg; } public static Boolean checkDate(String s){ Boolean ret = true; try{ DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); ret = df.format(df.parse(s)).equals(s); } catch(ParseException e){ ret = false; } return ret; } public Object dateinfo(String s){ String a[]=s.split("-",2); Hashtable fest =new Hashtable(); fest.put("01-01","元旦節(jié)"); fest.put("02-14","情人節(jié)"); fest.put("03-12","植樹節(jié)"); fest.put("03-15","消費(fèi)者節(jié)"); fest.put("04-01","愚人節(jié)"); fest.put("04-05","清明節(jié)"); fest.put("05-01","勞動(dòng)節(jié)"); fest.put("06-01","兒童節(jié)"); fest.put("07-01","建黨節(jié)"); fest.put("08-01","建軍節(jié)"); fest.put("09-10","教師節(jié)"); fest.put("10-01","國慶節(jié)"); fest.put("12-25","圣誕節(jié)"); if(fest.containsKey(a[1])){ return fest.get(a[1]); } else{ return "無節(jié)日"; } } public String xingzuo(Date s){ Calendar cal = Calendar.getInstance(); cal.setTime(s); String xingzuo="無"; int day=cal.get(Calendar.DAY_OF_YEAR); if((cal.get(Calendar.YEAR)%4==0)&&(cal.get(Calendar.YEAR)%100!=0)||(cal.get(Calendar.YEAR)%400==0)){ if((day>=1 &&day<=19)||(day>=357&&day<=366)){ xingzuo= "魔蝎座"; } else if(day>=20 &&day<=49){ xingzuo= "水瓶座"; } else if(day>=50 &&day<=80){ xingzuo= "雙魚座"; } else if(day>=81 &&day<=110){ xingzuo= "白羊座"; } else if(day>=111 &&day<=141){ xingzuo= "金牛座"; } else if(day>=142 &&day<=173){ xingzuo= "雙子座"; } else if(day>=174 &&day<=203){ xingzuo= "巨蟹座"; } else if(day>=204 &&day<=235){ xingzuo= "獅子座"; } else if(day>=236 &&day<=266){ xingzuo= "處女座"; } else if(day>=267 &&day<=296){ xingzuo= "天秤座"; } else if(day>=297 &&day<=326){ xingzuo= "天蝎座"; } else if(day>=327 &&day<=356){ xingzuo= "射手座"; } } else{ if((day>=1 &&day<=19)||(day>=357&&day<=366)){ xingzuo= "魔蝎座"; } else if(day>=20 &&day<=48){ xingzuo= "水瓶座"; } else if(day>=49 &&day<=79){ xingzuo= "雙魚座"; } else if(day>=80 &&day<=109){ xingzuo= "白羊座"; } else if(day>=110 &&day<=140){ xingzuo= "金牛座"; } else if(day>=141 &&day<=172){ xingzuo= "雙子座"; } else if(day>=173 &&day<=202){ xingzuo= "巨蟹座"; } else if(day>=203 &&day<=234){ xingzuo= "獅子座"; } else if(day>=235 &&day<=265){ xingzuo= "處女座"; } else if(day>=266 &&day<=295){ xingzuo= "天秤座"; } else if(day>=296 &&day<=325){ xingzuo= "天蝎座"; } else if(day>=326 &&day<=355){ xingzuo= "射手座"; } } return xingzuo; } public Date parseDate(String s){ SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { Date date3 = bartDateFormat.parse(s); date3=bartDateFormat.parse(s); return date3; } catch (Exception ex) { return null; } } public static void main(String[] args) { Calendar cal = Calendar.getInstance(); Test2 test2=new Test2(); String date1=JOptionPane.showInputDialog("請你輸入日期,格式如2000-10-15"); while(!(Test2.checkDate(date1)&&Test2.isdate(date1))){ date1=JOptionPane.showInputDialog("請你輸入日期,格式如2000-10-15"); } SimpleDateFormat bartDateFormat1 = new SimpleDateFormat("yyyy,MM,dd,EEEE"); SimpleDateFormat bartDateFormat2 = new SimpleDateFormat("yyyy-MM-dd"); Date date2=test2.parseDate(date1); String festinfo=(String)test2.dateinfo(date1); System.out.println(bartDateFormat1.format(date2) +","+ festinfo+","+ test2.xingzuo(date2)); String day=JOptionPane.showInputDialog("請你輸入要查詢N天后的日期信息"); cal.setTime(date2); cal.add(Calendar.DATE, Integer.parseint(day)); String date5=bartDateFormat2.format(cal.getTime()); festinfo=(String)test2.dateinfo(date5); System.out.println(bartDateFormat1.format(cal.getTime())+","+ festinfo+","+ test2.xingzuo(cal.getTime())); } }
以上是“java時(shí)間日期使用與查詢的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。