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 } }
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем:сервисные центры в ростове на дону
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
A few things i have usually told people today is that while looking for a good on-line electronics retail outlet, there are a few variables that you have to take into account. First and foremost, you should make sure to get a reputable and reliable retail store that has got great critiques and rankings from other people and market sector people. This will ensure that you are getting through with a well-known store that delivers good service and aid to their patrons. Thanks for sharing your opinions on this website.
kamagra senza ricetta in farmacia: viagra online siti sicuri – kamagra senza ricetta in farmacia
срочный ремонт кондиционера
As I web site possessor I believe the content material here is rattling wonderful , appreciate it for your efforts. You should keep it up forever! Good Luck.
Wonderful paintings! That is the type of information that should be shared around the net. Disgrace on the seek engines for no longer positioning this submit higher! Come on over and discuss with my website . Thanks =)
Hey, I think your blog might be having browser compatibility issues. When I look at your blog site in Chrome, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, amazing blog!
https://farmaciait.men/# Farmacia online miglior prezzo
farmacie online autorizzate elenco
farmacia online senza ricetta: Farmacia online piu conveniente – comprare farmaci online all’estero
п»їFarmacia online migliore Ibuprofene 600 prezzo senza ricetta farmacia online piГ№ conveniente
I do believe that a property foreclosure can have a important effect on the debtor’s life. House foreclosures can have a 7 to ten years negative effects on a applicant’s credit report. Any borrower who’s applied for home financing or just about any loans as an example, knows that your worse credit rating is usually, the more hard it is to obtain a decent mortgage. In addition, it could possibly affect a borrower’s capacity to find a quality place to lease or rent, if that results in being the alternative housing solution. Thanks for your blog post.
Farmacie on line spedizione gratuita Farmacie on line spedizione gratuita acquistare farmaci senza ricetta
You really make it seem so easy with your presentation but I in finding this matter to be really something that I think I might by no means understand. It sort of feels too complicated and very large for me. I am taking a look ahead for your subsequent publish, I?ll try to get the dangle of it!
comprare farmaci online all’estero Cialis generico prezzo farmacia online piГ№ conveniente
Попробуйте удачу на Cryptoboss Casino и выиграйте крупный джекпот
криптобосс официальный сайт криптобосс официальный сайт .
сервис профи самара
viagra generico sandoz viagra siti sicuri per comprare viagra online
сервисный центре предлагает ремонт телевизора – ремонт телевизоров с выездом на дом
instagram story viewer and downloader instagram story viewer and downloader .
Thanks for the tips you are discussing on this weblog. Another thing I would really like to say is getting hold of some copies of your credit file in order to examine accuracy of any detail could be the first measures you have to perform in repairing credit. You are looking to clean up your credit reports from dangerous details errors that spoil your credit score.
Thanks for these tips. One thing I also believe is the fact that credit cards supplying a 0 interest rate often attract consumers with zero monthly interest, instant endorsement and easy over-the-internet balance transfers, however beware of the main factor that will certainly void your current 0 easy road annual percentage rate as well as throw one out into the bad house rapid.
Отличный сайт! Всем рекомендую!Тут Вы можете заказатьвинтовые сваи купить спб
сервис кондиционеров
Hello there, You’ve performed an incredible job. I?ll certainly digg it and in my opinion recommend to my friends. I am sure they will be benefited from this website.
I know this if off topic but I’m looking into starting my own blog and was curious what all is required to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web savvy so I’m not 100 certain. Any recommendations or advice would be greatly appreciated. Appreciate it
Как выбрать коляску-люльку по всем правилам
люлька коляска для новорожденного https://koljaska-ljulka.ru/ .
alternativa al viagra senza ricetta in farmacia viagra prezzo viagra subito
In accordance with my study, after a the foreclosure home is available at an auction, it is common for that borrower in order to still have any remaining unpaid debt on the financial loan. There are many loan companies who try and have all expenses and liens paid off by the subsequent buyer. However, depending on selected programs, laws, and state laws and regulations there may be a few loans that are not easily fixed through the switch of loans. Therefore, the obligation still falls on the consumer that has acquired his or her property in foreclosure process. Thank you sharing your notions on this blog site.
Hello There. I discovered your blog the use of msn. That is a really smartly written article. I will be sure to bookmark it and return to learn more of your useful information. Thank you for the post. I will certainly comeback.
One other thing to point out is that an online business administration study course is designed for individuals to be able to easily proceed to bachelor’s degree education. The 90 credit college degree meets the lower bachelor college degree requirements then when you earn your own associate of arts in BA online, you’ll have access to the newest technologies in this field. Several reasons why students want to get their associate degree in business is because they can be interested in this area and want to find the general education and learning necessary in advance of jumping in a bachelor college diploma program. Thanks for the tips you provide within your blog.