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 } }
нарколог на дом анонимно http://narkolog-na-dom-krasnodar15.ru .
нарколог вывод из запоя ростов нарколог вывод из запоя ростов .
В магазине сейфов предлагают купить сейф в москве в магазине сейфов сейф цена москва
Stop by my blog: Daycares By Category
ozempic generic ozempic cost buy ozempic
Профессиональный сервисный центр по ремонту сетевых хранилищ в Москве.
Мы предлагаем: ремонт сетевого хранилища
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Heya this is somewhat of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding knowledge so I wanted to get guidance from someone with experience. Any help would be enormously appreciated!
https://ozempic.art/# ozempic online
Профессиональный сервисный центр ремонт телефонов по близости сервисный центр смартфонов
semaglutide tablets: buy semaglutide online – rybelsus coupon
Spot on with this write-up, I really assume this web site wants much more consideration. I?ll in all probability be again to learn much more, thanks for that info.
https://ozempic.art/# buy ozempic pills online
вывод из запоя дешево ростов на дону вывод из запоя дешево ростов на дону .
вывод. из. запоя. на. дому. ростов. вывод. из. запоя. на. дому. ростов. .
Профессиональный сервисный центр по ремонту автомагнитол в Москве.
Мы предлагаем: сервисные центры по ремонт автомагнитол
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Heya i?m for the primary time here. I came across this board and I in finding It truly useful & it helped me out a lot. I am hoping to give one thing back and aid others such as you helped me.
I appreciate, cause I found just what I was looking for. You have ended my 4 day long hunt! God Bless you man. Have a great day. Bye
F*ckin? remarkable issues here. I am very glad to see your article. Thank you a lot and i am looking forward to contact you. Will you please drop me a e-mail?
ozempic cost Ozempic without insurance ozempic coupon
вывод из запоя цена ростов вывод из запоя цена ростов .
Профессиональный сервисный центр по ремонту автомагнитол в Москве.
Мы предлагаем: ремонт автомагнитолы
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
вывод из запоя на дому ростов круглосуточно вывод из запоя на дому ростов круглосуточно .
http://ozempic.art/# buy cheap ozempic
http://ozempic.art/# Ozempic without insurance
Most of whatever you say is astonishingly precise and it makes me wonder the reason why I had not looked at this in this light before. This particular article truly did turn the light on for me personally as far as this subject matter goes. Nonetheless there is actually one point I am not too cozy with and whilst I make an effort to reconcile that with the actual central theme of your position, let me observe what all the rest of your subscribers have to say.Well done.
Профессиональный сервисный центр по ремонту сигвеев в Москве.
Мы предлагаем: надежный сервис ремонта сигвеев
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
ozempic cost: buy ozempic – ozempic coupon
ozempic cost Ozempic without insurance buy cheap ozempic
Stickman Ball Hook Game How to play: Click or tap to drop water, remove blocks and flip the glass. But beware! Each level presents new obstacles to overcome and other challenges that will make it difficult to get the water to the glass. You’ll need to think creatively and draw strategically to overcome each challenge and successfully fill the glass. Top 100 Games 3D Rolling Ball Game Pet Subway Surfers Game Have fun playing the game – and don´t forget: Play with your kids!*These links are affiliate links and play-with-your-kid might get a commission if you buy a product after using this link. Kung Fu Street Fight Game Click on a star to rate it! Card Games By embedding games on your website or application you are agreeing to the Construct.net Arcade Terms of Service.
https://www.smartinteriorlining.net.in/forum/general-discussions/stickman-shooting-games
Made of the highest quality food-grade silicone, BPA free, lead-free, phthalates free, soft and odorless, the smooth edge will not hurt your baby, don’t be worried about your baby playing or chewing, it is safe Kids always want to help out in the kitchen! Why not give them a kitchen of their own? This cooking set has all that they will need to start them on their culinary journey! This set has 20 pieces total including a tea kettle, frying pan, sauce pot, pressure cooker, cutting board, knife, crab, tomato, egg that can be cracked , and corn that can be shucked. Get their creativity cooking with our range of play food sets. Perfect for budding chefs and little foodies, our play food collection includes an assortment of play food, kid’s kitchen set ups, and even a store to sell it all in and so much more, all designed to inspire endless culinary adventures.
buy rybelsus online: rybelsus cost – buy semaglutide online