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 } }
Hello there! This is my first visit to your blog! We are a group of volunteers and starting a new project in a community in the same niche. Your blog provided us valuable information to work on. You have done a wonderful job!
hello there and thank you for your info ? I?ve certainly picked up anything new from right here. I did however expertise some technical issues using this website, since I experienced to reload the site lots of times previous to I could get it to load properly. I had been wondering if your hosting is OK? Not that I’m complaining, but slow loading instances times will sometimes affect your placement in google and could damage your high-quality score if advertising and marketing with Adwords. Anyway I am adding this RSS to my e-mail and can look out for a lot more of your respective exciting content. Make sure you update this again soon..
F*ckin? remarkable issues here. I?m very satisfied to peer your post. Thanks so much and i’m having a look forward to touch you. Will you please drop me a mail?
I appreciate your wordpress template, where did you download it through?
I have taken notice that in digital camera models, special receptors help to {focus|concentrate|maintain focus|target|a**** automatically. These sensors associated with some cams change in in the area of contrast, while others work with a beam with infra-red (IR) light, specifically in low light. Higher specification cameras at times use a mix of both models and likely have Face Priority AF where the dslr camera can ‘See’ a new face while keeping your focus only upon that. Thank you for sharing your notions on this blog site.
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем: сервис центры бытовой техники тюмень
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Great work! This is the type of information that should be shared around the internet. Shame on the search engines for not positioning this post higher! Come on over and visit my site . Thanks =)
Wonderful blog! I found it while browsing on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Appreciate it
india pharmacy: indian pharmacy – buy medicines online in india
mexico drug stores pharmacies: mexican border pharmacies shipping to usa – medicine in mexico pharmacies
Профессиональный сервисный центр по ремонту гироскутеров в Москве.
Мы предлагаем: сервис по ремонту гироскутеров
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Профессиональный сервисный центр по ремонту моноблоков в Москве.
Мы предлагаем: моноблок москва
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
http://canadapharma.shop/# ordering drugs from canada
vipps approved canadian online pharmacy: Canadian Pharmacy – canadian pharmacy near me
It’s best to participate in a contest for the most effective blogs on the web. I’ll advocate this website!
Online medicine order: indian pharmacy – best online pharmacy india
Oh my goodness! I’m in awe of the author’s writing skills and ability to convey complicated concepts in a straightforward and clear manner. This article is a true gem that merits all the praise it can get. Thank you so much, author, for offering your wisdom and giving us with such a valuable asset. I’m truly thankful!
Профессиональный сервисный центр по ремонту кондиционеров в Москве.
Мы предлагаем: ремонт кондиционеров москва недорого
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
I have read some good stuff here. Certainly worth bookmarking for revisiting. I wonder how much effort you put to create such a excellent informative website.
https://indiadrugs.pro/# top 10 online pharmacy in india
Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт цифровой техники воронеж
снять проститутку снять проститутку .
I have seen plenty of useful items on your website about desktops. However, I have got the view that notebook computers are still more or less not powerful more than enough to be a good choice if you often do things that require lots of power, for example video touch-ups. But for web surfing, word processing, and a lot other popular computer work they are just fine, provided you can’t mind the tiny screen size. Thanks for sharing your ideas.
Thanks a lot for sharing this with all of us you actually know what you are talking about! Bookmarked. Kindly also visit my website =). We could have a link exchange agreement between us!
I believe that a foreclosures can have a major effect on the debtor’s life. House foreclosures can have a 7 to a decade negative affect on a applicant’s credit report. A new borrower who’s applied for home financing or just about any loans even, knows that the worse credit rating is, the more complicated it is to have a decent mortgage. In addition, it might affect the borrower’s ability to find a really good place to let or hire, if that becomes the alternative housing solution. Thanks for your blog post.
Профессиональный сервисный центр по ремонту моноблоков в Москве.
Мы предлагаем: ремонт моноблоков
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Профессиональный сервисный центр по ремонту гироскутеров в Москве.
Мы предлагаем: цены на ремонт гироскутеров
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
One other issue is when you are in a circumstances where you will not have a cosigner then you may want to try to make use of all of your federal funding options. You will discover many awards and other scholarships and grants that will supply you with money that can help with college expenses. Thanks alot : ) for the post.
ed meds online canada: Online medication home delivery – canada drugs online
Great blog here! Also your website loads up very fast! What host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as quickly as yours lol