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://tadalafilo.bid/# farmacia online barcelona
farmacia online envГo gratis
http://sildenafilo.men/# sildenafilo 50 mg precio sin receta
farmacia online madrid
viagra online cerca de la coruГ±a: viagra generico – sildenafilo cinfa 25 mg precio
https://sildenafilo.men/# viagra online cerca de zaragoza
farmacia en casa online descuento: cialis en Espana sin receta contrareembolso – farmacia en casa online descuento
Hey there would you mind stating which blog platform you’re using? I’m going to start my own blog in the near future but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something completely unique. P.S My apologies for being off-topic but I had to ask!
farmacia online barata y fiable: Cialis generico – п»їfarmacia online espaГ±a
https://farmaciaeu.com/# farmacia online barcelona
Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники в тюмени
farmacias online seguras en espaГ±a: farmacia online envio gratis valencia – farmacia online envГo gratis
https://tadalafilo.bid/# farmacias online seguras en espaГ±a
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: ремонт крупногабаритной техники в перми
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Thank you for any other great article. The place else could anyone get that kind of info in such a perfect means of writing? I’ve a presentation subsequent week, and I’m at the search for such info.
Attractive part of content. I just stumbled upon your blog and in accession capital to claim that I get in fact enjoyed account your blog posts. Anyway I will be subscribing to your feeds and even I fulfillment you get admission to consistently quickly.
A formidable share, I just given this onto a colleague who was doing a little analysis on this. And he in fact bought me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I really feel strongly about it and love studying extra on this topic. If attainable, as you grow to be expertise, would you thoughts updating your weblog with extra details? It’s extremely helpful for me. Massive thumb up for this blog publish!
We stumbled over here coming from a different web page and thought I may as well check things out. I like what I see so i am just following you. Look forward to looking over your web page yet again.
Профессиональный сервисный центр по ремонту кнаручных часов от советских до швейцарских в Москве.
Мы предлагаем: ремонт часов цена
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
I like the helpful information you provide in your articles. I?ll bookmark your blog and check again here frequently. I am quite sure I will learn many new stuff right here! Good luck for the next!
you’re really a just right webmaster. The web site loading speed is incredible. It sort of feels that you are doing any unique trick. Also, The contents are masterpiece. you’ve performed a excellent task on this topic!
farmacia online espaГ±a envГo internacional: cialis en Espana sin receta contrareembolso – п»їfarmacia online espaГ±a
I can’t express how much I admire the effort the author has put into creating this remarkable piece of content. The clarity of the writing, the depth of analysis, and the abundance of information provided are simply impressive. His passion for the subject is evident, and it has undoubtedly made an impact with me. Thank you, author, for providing your knowledge and enhancing our lives with this incredible article!
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: ремонт крупногабаритной техники в перми
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
That is very fascinating, You are an excessively skilled blogger. I have joined your feed and look forward to searching for more of your fantastic post. Also, I have shared your web site in my social networks!
It’s a shame you don’t have a donate button! I’d without a doubt donate to this superb blog! I suppose for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to fresh updates and will talk about this site with my Facebook group. Chat soon!
farmacias online seguras: Comprar Cialis sin receta – farmacia online 24 horas
http://tadalafilo.bid/# farmacias online seguras en espaГ±a
farmacia online barata
I figured out more something totally new on this weight loss issue. One particular issue is a good nutrition is very vital whenever dieting. A massive reduction in junk food, sugary food, fried foods, sugary foods, beef, and white colored flour products may be necessary. Retaining wastes harmful bacteria, and toxic compounds may prevent objectives for losing weight. While certain drugs quickly solve the challenge, the bad side effects aren’t worth it, and in addition they never offer you more than a short-lived solution. It is a known incontrovertible fact that 95 of diet plans fail. Thank you for sharing your notions on this blog site.
Appreciating the hard work you put into your site and in depth information you provide. It’s great to come across a blog every once in a while that isn’t the same unwanted rehashed material. Fantastic read! I’ve saved your site and I’m including your RSS feeds to my Google account.
There are actually lots of particulars like that to take into consideration. That could be a great level to carry up. I supply the thoughts above as basic inspiration but clearly there are questions just like the one you bring up the place a very powerful thing will likely be working in trustworthy good faith. I don?t know if finest practices have emerged round issues like that, but I am sure that your job is clearly recognized as a good game. Each boys and girls really feel the influence of just a second?s pleasure, for the rest of their lives.
I was recommended this web site by way of my cousin. I’m no longer positive whether or not this post is written by means of him as nobody else know such detailed about my problem. You’re amazing! Thanks!