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 } }
Thanks for the sensible critique. Me and my neighbor were just preparing to do a little research on this. We got a grab a book from our local library but I think I learned more from this post. I’m very glad to see such excellent info being shared freely out there.
meloxicam 15mg canada – maxalt 5mg oral buy ketorolac generic
Hmm is anyone else having problems with the images on this blog loading? I’m trying to find out if its a problem on my end or if it’s the blog. Any suggestions would be greatly appreciated.
Профессиональный сервисный центр по ремонту фото техники от зеркальных до цифровых фотоаппаратов.
Мы предлагаем: ремонт проектора
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
http://farmaciaeu.com/# farmacia en casa online descuento
farmacia online 24 horas
http://tadalafilo.bid/# farmacias direct
farmacias online seguras en espaГ±a
farmacia online envГo gratis Comprar Cialis sin receta farmacia online madrid
farmacia online barata: farmacia online 24 horas – farmacias online seguras en espaГ±a
Если вы искали где отремонтировать сломаную технику, обратите внимание – профи тех сервис тюмень
Aw, this was a really nice post. In idea I wish to put in writing like this moreover ? taking time and actual effort to make a very good article? however what can I say? I procrastinate alot and not at all appear to get one thing done.
One thing is that often one of the most common incentives for using your credit card is a cash-back and also rebate offer. Generally, you’ll receive 1-5 back in various buying. Depending on the credit cards, you may get 1 back again on most purchases, and 5 back again on expenditures made on convenience stores, filling stations, grocery stores as well as ‘member merchants’.
viagra online cerca de zaragoza: viagra precio – viagra para hombre precio farmacias
Профессиональный сервисный центр по ремонту кнаручных часов от советских до швейцарских в Москве.
Мы предлагаем: срочный ремонт часов
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Профессиональный сервисный центр по ремонту мониторов в Москве.
Мы предлагаем: ремонт мониторов на дому
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Thanks for expressing your ideas in this article. The other element is that each time a problem appears with a laptop or computer motherboard, persons should not take the risk with repairing that themselves for if it is not done correctly it can lead to permanent damage to all the laptop. It is almost always safe just to approach a dealer of a laptop for any repair of the motherboard. They’ve already technicians who have an competence in dealing with pc motherboard complications and can make the right prognosis and execute repairs.
Thanks for your posting. One other thing is the fact individual states in the United states of america have their unique laws which affect homeowners, which makes it quite difficult for the the nation’s lawmakers to come up with a whole new set of rules concerning foreclosure on home owners. The problem is that every state provides own regulations which may have impact in an unwanted manner in relation to foreclosure guidelines.
I’ve been absent for a while, but now I remember why I used to love this website. Thanks , I will try and check back more frequently. How frequently you update your web site?
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: сервисные центры в нижнем новгороде
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
https://tadalafilo.bid/# п»їfarmacia online espaГ±a
farmacia online barata
https://sildenafilo.men/# venta de viagra a domicilio
farmacia online madrid: comprar cialis original – farmacias online seguras
This website does not show up properly on my iphone 4 – you might want to try and fix that
farmacia online 24 horas farmacia online envio gratis murcia farmacias online seguras en espaГ±a
http://farmaciaeu.com/# farmacia online barata
venta de viagra a domicilio: viagra precio – farmacia gibraltar online viagra
farmacias online baratas: Precio Cialis 20 Mg – farmacia online madrid
http://sildenafilo.men/# se puede comprar sildenafil sin receta
Just wish to say your article is as surprising. The clarity to your publish is just nice and that i can think you’re a professional in this subject. Fine with your permission let me to take hold of your RSS feed to stay up to date with coming near near post. Thanks one million and please keep up the rewarding work.
Hey there! I know this is kind of off topic but I was wondering which blog platform are you using for this website? I’m getting sick and tired of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform. I would be awesome if you could point me in the direction of a good platform.
farmacia online envГo gratis precio cialis en farmacia con receta farmacias online seguras en espaГ±a