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 } }
There are certainly a whole lot of particulars like that to take into consideration. That may be a nice level to bring up. I offer the thoughts above as general inspiration but clearly there are questions just like the one you carry up where crucial thing can be working in sincere good faith. I don?t know if best practices have emerged round issues like that, but I am positive that your job is clearly identified as a fair game. Each girls and boys really feel the affect of just a moment?s pleasure, for the remainder of their lives.
A person essentially help to make seriously posts I would state. This is the first time I frequented your web page and thus far? I amazed with the research you made to make this particular publish extraordinary. Wonderful job!
Быстрая покупка диплома старого образца: возможные риски
Excellent post. I used to be checking continuously this weblog and I’m inspired! Extremely helpful information specially the closing phase 🙂 I deal with such info much. I used to be looking for this particular information for a long time. Thank you and best of luck.
Как быстро и легально купить аттестат 11 класса в Москве
Hey are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you need any coding knowledge to make your own blog? Any help would be really appreciated!
вывод из запоя цена ростов https://www.business.0pk.me/viewtopic.php?id=37942#p224618 .
срочный вывод из запоя ростов http://rubiz.forum.cool/viewtopic.php?id=3742 .
вывод из запоя на дому ростов круглосуточно https://zarabotokdoma.creartuforo.com/viewtopic.php?id=11470 .
Thanks for the distinct tips provided on this web site. I have seen that many insurance firms offer shoppers generous discounts if they favor to insure multiple cars with them. A significant variety of households own several vehicles these days, particularly those with more mature teenage young children still living at home, as well as savings in policies might soon mount up. So it is a good idea to look for a bargain.
Thanks for the suggestions about credit repair on this blog. A few things i would offer as advice to people is usually to give up this mentality that they’ll buy at this point and pay back later. As being a society we tend to make this happen for many factors. This includes vacation trips, furniture, as well as items we wish. However, you should separate your wants from the needs. When you are working to boost your credit score you have to make some sacrifices. For example you can shop online to save cash or you can go to second hand retailers instead of high-priced department stores regarding clothing.
вывод из запоя на дому ростов http://www.forumsilverstars.forum24.ru/?1-2-0-00000146-000-0-0-1730649531/ .
Hey very cool website!! Man .. Beautiful .. Amazing .. I’ll bookmark your website and take the feeds also?I am happy to find so many useful information here in the post, we need work out more strategies in this regard, thanks for sharing. . . . . .
вывод из запоя ростов-на-дону https://www.masa.forum24.ru/?1-16-0-00002618-000-0-0-1730649347 .
Based on my study, after a in foreclosure home is offered at a bidding, it is common for that borrower to still have a remaining balance on the personal loan. There are many loan merchants who make an effort to have all fees and liens cleared by the subsequent buyer. Nevertheless, depending on a number of programs, restrictions, and state laws there may be several loans that aren’t easily solved through the transfer of loans. Therefore, the responsibility still remains on the consumer that has received his or her property foreclosed on. Thank you sharing your opinions on this website.
you’re in point of fact a excellent webmaster. The site loading speed is amazing. It sort of feels that you’re doing any unique trick. Also, The contents are masterpiece. you’ve performed a wonderful process on this topic!
mexican mail order pharmacies: medicines mexico rx online – mexican mail order pharmacies
This is really interesting, You are a very skilled blogger. I have joined your rss feed and look forward to seeking more of your fantastic post. Also, I have shared your web site in my social networks!
I’m not sure why but this blog is loading incredibly slow for me. Is anyone else having this problem or is it a issue on my end? I’ll check back later on and see if the problem still exists.
Whats up! I simply want to give an enormous thumbs up for the great info you’ve gotten here on this post. I will probably be coming again to your blog for more soon.
Your house is valueble for me. Thanks!?
https://mexicanpharmgate.com/# mexico pharmacies prescription drugs
Thanks a lot for your post. I’d really like to say that the expense of car insurance varies from one coverage to another, since there are so many different issues which bring about the overall cost. For example, the model and make of the auto will have a huge bearing on the cost. A reliable older family motor vehicle will have a less expensive premium than the usual flashy performance car.
Hello! Someone in my Myspace group shared this site with us so I came to check it out. I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers! Excellent blog and wonderful design and style.
продамус промокод скидка http://prodamus-promokod21.ru .
Как не стать жертвой мошенников при покупке диплома о среднем полном образовании
Thanks for another informative website. Where else could I get that kind of information written in such a perfect way? I’ve a project that I’m just now working on, and I’ve been on the look out for such info.
I have viewed that sensible real estate agents everywhere you go are Promotion. They are realizing that it’s not just placing a poster in the front area. It’s really concerning building connections with these vendors who later will become consumers. So, while you give your time and energy to assisting these vendors go it alone : the “Law associated with Reciprocity” kicks in. Great blog post.
Great beat ! I would like to apprentice while you amend your web site, how could i subscribe for a blog site? The account aided me a acceptable deal. I had been tiny bit acquainted of this your broadcast provided bright clear concept
I’m extremely inspired along with your writing skills as smartly as with the structure in your blog. Is that this a paid topic or did you customize it yourself? Anyway stay up the excellent high quality writing, it is rare to look a great weblog like this one these days..