Java 各種時間上的操作範例
分享一些在專案中用到JAVA與日期相關的操作,包括:
- 取得目前的年、月、日
- 判斷兩個日期的大小
- 計算兩個日期的差距
- 取得昨天的日期
- 取得上個月的開始與結束日
package CDIT.stanley; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Calendar; public class dateOperation { public static int differentDays(Date date1,Date date2){ Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); int day1= cal1.get(Calendar.DAY_OF_YEAR); int day2 = cal2.get(Calendar.DAY_OF_YEAR); int year1 = cal1.get(Calendar.YEAR); int year2 = cal2.get(Calendar.YEAR); if(year1 != year2){ int timeDistance = 0 ; for(int i = year1 ; i < year2 ; i ++){ if(i%4==0 && i%100!=0 || i%400==0){ timeDistance += 366; } else{ timeDistance += 365; } } return timeDistance + (day2-day1) ; } else{ return day2-day1; } } public static Date getFirstMonthDay(Calendar calendar) { calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DATE)); return calendar.getTime(); } public static Date getLastMonthDay(Calendar calendar) { calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE)); return calendar.getTime(); } public static void main(String[] args) throws ParseException { //取得目前的年、月、日 Calendar calendar = Calendar.getInstance(); System.out.println("今天是" + calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日"); System.out.println("=================================================="); //輸出:今天是2017年8月24日 //判斷兩個日期的大小 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN); Date date1 = sdf.parse("2017-08-23"); Date date2 = sdf.parse("2016-09-22"); System.out.println("Date1 < Date2 : " + date1.before(date2)); System.out.println("Date1 > Date2 : " + date1.after(date2)); System.out.println("=================================================="); //輸出:Date1 < Date2 : false、Date1 > Date2 : true //計算兩個日期的差距 System.out.println("Date1 & Date2 差距 : " + differentDays(date1 , date2) + "天"); System.out.println("=================================================="); //輸出:Date1 & Date2 差距 : 31天 //取得昨天的日期 calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, -1); String yestedayDate = sdf.format(calendar.getTime()); System.out.println("昨天是" + yestedayDate); System.out.println("=================================================="); //輸出:昨天是2017-08-23 //取得上個月的開始與結束日 calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH,-1); String monthDayFirst = sdf.format(getFirstMonthDay(calendar)); String monthDayLast = sdf.format(getLastMonthDay(calendar)); System.out.println("上個月的第一天是" + monthDayFirst); System.out.println("上個月的最後一天是" + monthDayLast); System.out.println("=================================================="); //輸出:上個月的第一天是2017-07-01、上個月的最後一天是2017-07-31 } }
naturally like your web site but you need to take a look at the spelling on several of your posts. A number of them are rife with spelling issues and I in finding it very troublesome to tell the truth however I will surely come back again.
I’m very happy to read this. This is the type of manual that needs to be given and not the accidental misinformation that’s at the other blogs. Appreciate your sharing this greatest doc.
Great work! That is the type of info that are meant to be shared across the web. Disgrace on Google for no longer positioning this post higher! Come on over and seek advice from my website . Thanks =)
This is really interesting, You are a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your fantastic post. Also, I have shared your site in my social networks!
Simply want to say your article is as surprising. The clarity in your post is simply nice and i can assume you are an expert on this subject. Well with your permission let me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please continue the rewarding work.
Interesting article. It is extremely unfortunate that over the last years, the travel industry has already been able to to fight terrorism, SARS, tsunamis, bird flu virus, swine flu, along with the first ever entire global economic collapse. Through all of it the industry has proven to be solid, resilient and also dynamic, getting new tips on how to deal with misfortune. There are constantly fresh complications and chance to which the industry must once again adapt and answer.
Somebody essentially assist to make significantly articles I might state. This is the first time I frequented your website page and to this point? I surprised with the analysis you made to make this particular publish extraordinary. Excellent job!
Thanks for your post. I would also love to say that a health insurance brokerage service also utilizes the benefit of the particular coordinators of your group insurance policies. The health insurance professional is given a listing of benefits searched for by anyone or a group coordinator. Exactly what a broker does is find individuals or perhaps coordinators which best go with those demands. Then he offers his recommendations and if both sides agree, the particular broker formulates binding agreement between the 2 parties.
An attention-grabbing dialogue is price comment. I think that you must write more on this matter, it may not be a taboo topic but usually persons are not sufficient to speak on such topics. To the next. Cheers
The other day, while I was at work, my cousin stole my apple ipad and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My apple ipad is now destroyed and she has 83 views. I know this is entirely off topic but I had to share it with someone!
hi!,I like your writing very much! share we communicate more about your post on AOL? I need an expert on this area to solve my problem. May be that’s you! Looking forward to see you.
Music started playing as soon as I opened this web page, so annoying!
Yet another thing I would like to mention is that rather than trying to accommodate all your online degree training on days that you end work (since the majority people are drained when they get back), try to arrange most of your classes on the saturdays and sundays and only a few courses for weekdays, even if it means a little time off your end of the week. This is really good because on the weekends, you will be far more rested along with concentrated in school work. Thanks alot : ) for the different points I have realized from your website.
hey there and thank you for your information ? I?ve certainly picked up something new from right here. I did however expertise some technical issues using this web site, as I experienced to reload the site a lot of times previous to I could get it to load properly. I had been wondering if your hosting is OK? Not that I’m complaining, but sluggish loading instances times will sometimes affect your placement in google and can damage your high quality score if ads and marketing with Adwords. Anyway I am adding this RSS to my e-mail and can look out for much more of your respective intriguing content. Ensure that you update this again soon..
Just desire to say your article is as amazing. The clearness for your publish is just spectacular and that i could suppose you are knowledgeable in this subject. Fine together with your permission allow me to seize your feed to keep updated with coming near near post. Thank you a million and please continue the gratifying work.
F*ckin? awesome things here. I?m very glad to see your post. Thanks a lot and i’m looking forward to contact you. Will you kindly drop me a e-mail?
Do you have a spam issue on this site; I also am a blogger, and I was wanting to know your situation; many of us have created some nice procedures and we are looking to trade methods with other folks, why not shoot me an e-mail if interested.
Also visit my web blog; Daycares By Category
Your website won’t render properly on my apple iphone – you may wanna try and repair that
Hi there, You have performed a fantastic job. I?ll definitely digg it and in my opinion recommend to my friends. I’m sure they’ll be benefited from this website.
deneme bonusu veren siteler: yasal slot siteleri – en iyi slot siteleri
slot siteleri guvenilir: bonus veren slot siteleri – oyun siteleri slot
I have learned some important things through your post. I might also like to convey that there might be situation where you will make application for a loan and do not need a cosigner such as a National Student Support Loan. But if you are getting a loan through a conventional loan company then you need to be ready to have a co-signer ready to assist you to. The lenders are going to base their decision on the few variables but the most significant will be your credit rating. There are some loan companies that will additionally look at your work history and determine based on this but in many instances it will be based on on your score.
Hello, i think that i saw you visited my website so i came to ?return the favor?.I am attempting to find things to improve my web site!I suppose its ok to use a few of your ideas!!
Thanks for your post on the travel industry. We would also like to add that if you are a senior thinking of traveling, its absolutely crucial that you buy traveling insurance for seniors. When traveling, seniors are at biggest risk of getting a healthcare emergency. Obtaining right insurance policies package for one’s age group can protect your health and provide peace of mind.
Can I simply say what a aid to seek out somebody who truly is aware of what theyre talking about on the internet. You undoubtedly know find out how to carry an issue to mild and make it important. More people have to learn this and understand this aspect of the story. I cant consider youre no more in style because you undoubtedly have the gift.
Hi there, I found your website by the use of Google whilst looking for a comparable matter, your site came up, it appears good. I’ve bookmarked it in my google bookmarks.
Thanks for your submission. I also think laptop computers have become more and more popular these days, and now in many cases are the only type of computer found in a household. Simply because at the same time they are becoming more and more cost-effective, their computing power is growing to the point where they can be as effective as pc’s coming from just a few years ago.
I just could not depart your website before suggesting that I extremely enjoyed the standard information a person provide for your visitors? Is gonna be back often to check up on new posts
Interesting blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog shine. Please let me know where you got your design. Bless you