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 } }
Have you ever thought about creating an ebook or guest authoring on other sites? I have a blog centered on the same topics you discuss and would love to have you share some stories/information. I know my readers would appreciate your work. If you’re even remotely interested, feel free to shoot me an e-mail.
Thanks a lot for the helpful write-up. It is also my opinion that mesothelioma cancer has an incredibly long latency period, which means that warning signs of the disease might not exactly emerge until finally 30 to 50 years after the original exposure to asbestos fiber. Pleural mesothelioma, which can be the most common kind and has an effect on the area around the lungs, might result in shortness of breath, chest pains, as well as a persistent cough, which may cause coughing up maintain.
Hello, i feel that i noticed you visited my blog thus i came to ?return the desire?.I’m attempting to in finding things to improve my site!I assume its adequate to use a few of your ideas!!
Thanks for your article. I would love to say that a health insurance dealer also utilizes the benefit of the actual coordinators of the group insurance policy. The health insurance agent is given a directory of benefits searched for by anyone or a group coordinator. What a broker can is look for individuals or maybe coordinators that best go with those requirements. Then he gifts his suggestions and if the two of you agree, the actual broker formulates a legal contract between the 2 parties.
I really like your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it for you? Plz answer back as I’m looking to create my own blog and would like to know where u got this from. thanks a lot
Youre so cool! I dont suppose Ive read anything like this before. So nice to find somebody with some authentic ideas on this subject. realy thank you for beginning this up. this web site is something that’s wanted on the web, someone with a little originality. useful job for bringing one thing new to the internet!
Wonderful web site. Plenty of useful information here. I am sending it to several buddies ans also sharing in delicious. And certainly, thank you to your sweat!
Helpful information. Fortunate me I found your web site by accident, and I am shocked why this coincidence didn’t came about earlier! I bookmarked it.
Thanks a lot for sharing this with all of us you really know what you’re talking about! Bookmarked. Kindly also visit my web site =). We could have a link exchange arrangement between us!
https://mexstarpharma.online/# mexican drugstore online
I think that is one of the most significant info for me. And i am glad reading your article. But wanna commentary on some common issues, The web site style is ideal, the articles is in point of fact nice : D. Just right activity, cheers
Also visit my webpage Daycares popular listings (http://www.usveterans.us)
http://easyrxindia.com/# indian pharmacies safe
http://mexstarpharma.com/# mexico pharmacies prescription drugs
canadian online pharmacy: canadian pharmacy online – canadian pharmacy online store
One thing is always that one of the most prevalent incentives for applying your credit card is a cash-back as well as rebate offer. Generally, you’ll receive 1-5 back in various acquisitions. Depending on the credit card, you may get 1 again on most purchases, and 5 back on expenses made at convenience stores, gas stations, grocery stores and also ‘member merchants’.
Yet another thing is that when evaluating a good on the net electronics store, look for web stores that are continually updated, retaining up-to-date with the most current products, the most beneficial deals, along with helpful information on product or service. This will ensure that you are handling a shop that stays over the competition and provide you what you should need to make intelligent, well-informed electronics expenditures. Thanks for the essential tips I have really learned through your blog.
whoah this weblog is great i really like studying your posts. Stay up the great work! You understand, many persons are hunting round for this information, you could help them greatly.
One other issue issue is that video games are generally serious naturally with the key focus on mastering rather than fun. Although, there’s an entertainment aspect to keep your children engaged, just about every game is generally designed to work towards a specific expertise or course, such as instructional math or scientific disciplines. Thanks for your posting.
I have not checked in here for some time as I thought it was getting boring, but the last few posts are good quality so I guess I will add you back to my everyday bloglist. You deserve it my friend 🙂
Les avocats et conseillers financiers Fintech de RUE (Regulated United Europe) ont cree un blog ou ils publient les dernieres modifications de la legislation des pays europeens dans le domaine de la crypto-monnaie et du VASP (Virtual Asset Fournisseur de services) pour la commodite et l’information de tous ceux qui s’interessent a la legislation europeenne sur les crypto-monnaies. Nous basons nos articles sur des sujets importants pour les entrepreneurs d’aujourd’hui travaillant dans le domaine de la crypto-monnaie, des projets fintech, de la blockchain et des entreprises liees a l’informatique. Si vous ne trouvez pas les informations qui vous interessent sur notre blog, veuillez nous contacter de la maniere qui vous convient.
I simply could not go away your site prior to suggesting that I extremely enjoyed the standard information an individual provide to your visitors? Is gonna be back frequently in order to check out new posts
Thanks for expressing your ideas listed here. The other thing is that every time a problem develops with a pc motherboard, folks should not take the risk regarding repairing the item themselves because if it is not done properly it can lead to irreparable damage to the whole laptop. It is usually safe just to approach any dealer of your laptop for any repair of the motherboard. They’ve already technicians who have an knowledge in dealing with notebook motherboard problems and can get the right analysis and accomplish repairs.
I do agree with all the ideas you’ve presented in your post. They’re very convincing and will certainly work. Still, the posts are too short for starters. Could you please extend them a little from next time? Thanks for the post.
I have observed that over the course of developing a relationship with real estate proprietors, you’ll be able to get them to understand that, in each and every real estate financial transaction, a payment is paid. Eventually, FSBO sellers don’t “save” the payment. Rather, they fight to earn the commission by way of doing the agent’s job. In this, they expend their money as well as time to carry out, as best they are able to, the responsibilities of an agent. Those assignments include disclosing the home by way of marketing, presenting the home to buyers, making a sense of buyer emergency in order to trigger an offer, preparing home inspections, controlling qualification inspections with the loan company, supervising fixes, and facilitating the closing of the deal.
Thanks for your post. One other thing is when you are advertising your property all on your own, one of the difficulties you need to be conscious of upfront is just how to deal with property inspection records. As a FSBO retailer, the key about successfully shifting your property as well as saving money in real estate agent revenue is information. The more you know, the more stable your property sales effort will be. One area where this is particularly essential is information about home inspections.
very good put up, i certainly love this web site, carry on it
Just about all of what you state is supprisingly accurate and it makes me wonder the reason why I hadn’t looked at this with this light previously. This particular piece really did turn the light on for me personally as far as this subject matter goes. However at this time there is actually just one position I am not too cozy with and whilst I try to reconcile that with the central theme of your point, allow me observe what all the rest of your subscribers have to point out.Nicely done.
I do agree with all the ideas you have presented in your post. They’re very convincing and will certainly work. Still, the posts are too short for novices. Could you please extend them a bit from next time? Thanks for the post.
Nice post. I learn one thing more challenging on completely different blogs everyday. It’s going to always be stimulating to learn content from different writers and apply slightly one thing from their store. I?d favor to use some with the content material on my weblog whether or not you don?t mind. Natually I?ll offer you a hyperlink in your web blog. Thanks for sharing.