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 } }
https://ameblo.jp/naveridbuy/entry-12866331149.html
Thanks for your intriguing article. One other problem is that mesothelioma is generally attributable to the breathing of fibers from asbestos, which is a carcinogenic material. Its commonly witnessed among staff in the engineering industry who definitely have long experience of asbestos. It’s also caused by moving into asbestos insulated buildings for some time of time, Genetic makeup plays a huge role, and some persons are more vulnerable towards the risk as compared to others.
One thing I have actually noticed is that often there are plenty of fallacies regarding the banking institutions intentions while talking about property foreclosure. One fantasy in particular would be the fact the bank needs to have your house. The lending company wants your dollars, not your property. They want the cash they loaned you together with interest. Keeping away from the bank is only going to draw a foreclosed conclusion. Thanks for your article.
https://predpharmnet.shop/# over the counter prednisone pills
prednisone without prescription medication Pred Pharm Net prednisone pill
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем:ремонт крупногабаритной техники в москве
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Thanks for expressing your ideas. One thing is that college students have a selection between government student loan plus a private student loan where its easier to opt for student loan debt consolidation than over the federal student loan.
Clom Fast Pharm: can you get generic clomid pills – Clom Fast Pharm
generic for amoxicillin: AmOnlinePharm – amoxicillin 500mg capsules
Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is magnificent, as well as the content!
Major thankies for the blog. Want more.
buy amoxicillin 500mg capsules uk: amoxicillin 500mg price in canada – AmOnlinePharm
These days of austerity along with relative anxiety about getting debt, lots of people balk contrary to the idea of employing a credit card to make purchase of merchandise or even pay for a trip, preferring, instead to rely on a tried along with trusted way of making repayment – raw cash. However, if you’ve got the cash available to make the purchase fully, then, paradoxically, that’s the best time for you to use the cards for several reasons.
lisinopril 20 25 mg tab: Lisin Express – how much is lisinopril 40 mg
Uncertain whether a secured loan is right for you? Understand the benefits, such as more favourable terms and larger borrowing amounts.
AmOnlinePharm: AmOnlinePharm – amoxicillin 250 mg
One important thing is that while you are searching for a student loan you may find that you’ll need a cosigner. There are many circumstances where this is true because you could find that you do not employ a past credit history so the loan provider will require that you have someone cosign the loan for you. Interesting post.
I do accept as true with all the concepts you’ve introduced to your post. They’re very convincing and will certainly work. Nonetheless, the posts are too brief for novices. May you please prolong them a bit from subsequent time? Thank you for the post.
https://amonlinepharm.com/# AmOnlinePharm
Thinking about a loan against your home to manage your debts? Find out more and check what solutions may be available to you.
Clom Fast Pharm Clom Fast Pharm can you buy clomid for sale
https://medium.com/@1kelly76/%EB%B9%84%EC%95%84%EA%B7%B8%EB%9D%BC-%EA%B5%AC%EB%A7%A4-%EC%A0%84-%EC%96%B4%EB%96%A4-%EA%B2%83%EC%9D%84-%EA%B3%A0%EB%A0%A4%ED%95%B4%EC%95%BC-%ED%95%A0%EA%B9%8C-743d5cd4580e
It’s a shame you don’t have a donate button! I’d most certainly donate to this superb blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to brand new updates and will share this blog with my Facebook group. Chat soon!
Clom Fast Pharm: Clom Fast Pharm – where can i get cheap clomid for sale
great points altogether, you simply gained a new reader. What would you recommend about your post that you made a few days in the past? Any sure?
Attractive element of content. I simply stumbled upon your site and in accession capital to claim that I acquire in fact enjoyed account your blog posts. Anyway I will be subscribing to your feeds or even I success you access constantly rapidly.
I’m not sure exactly why but this web site is loading incredibly slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later on and see if the problem still exists.
I have noticed that over the course of constructing a relationship with real estate owners, you’ll be able to get them to understand that, in each and every real estate financial transaction, a payment is paid. Ultimately, FSBO sellers really don’t “save” the commission payment. Rather, they try to win the commission by doing an agent’s work. In doing so, they spend their money plus time to conduct, as best they might, the obligations of an realtor. Those responsibilities include getting known the home through marketing, showing the home to willing buyers, building a sense of buyer emergency in order to make prompt an offer, scheduling home inspections, handling qualification assessments with the loan provider, supervising maintenance, and facilitating the closing.
https://predpharmnet.shop/# buy prednisone online canada
One other issue issue is that video games can be serious as the name indicated with the most important focus on finding out rather than amusement. Although, it comes with an entertainment part to keep your young ones engaged, every single game will likely be designed to focus on a specific expertise or programs, such as mathematics or scientific research. Thanks for your article.