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 } }
The Profit Cap might not be applied to your Universal Credit funds for 9 months after you stopped incomes.
The blushing bride wore an ivory Chantilly lace gown designed by Carmen Marc Valvo closely embellished with beading and embroidery, which she had picked out only every week earlier than the date.
I have carried out this only to find that the light was defective.
Как купить диплом о высшем образовании с минимальными рисками
I can’t express how much I value the effort the author has put into writing this exceptional piece of content. The clarity of the writing, the depth of analysis, and the wealth of information presented are simply remarkable. Her zeal for the subject is evident, and it has certainly struck a chord with me. Thank you, author, for providing your knowledge and enlightening our lives with this exceptional article!
A proposed quarry in Kent might destroy even more historical woodland websites than HS2 and Lower Thames Crossing combined, says the Woodland Trust.
This is really attention-grabbing, You are an excessively skilled blogger. I’ve joined your rss feed and look forward to searching for extra of your excellent post. Additionally, I have shared your website in my social networks!
buy amoxicillin online mexico https://clomidrexpharm.com/# where to buy clomid online
It’s enjoyable for infants and toddlers to drop or throw food on the floor.
Узнай все о на что влияет варикоцеле варикоцеле причины
Larbert Establishment Studies 1892-1901.
2. When are you moving?
Shaker-impressed, deceptively easy wood cabinets carry the graceful scheme along, but their sinuous design curves like a meandering stream across the room.
Your site does not render appropriately on my blackberry – you may wanna try and fix that
purchase amoxicillin 500 mg Amoxicillin buy online amoxicillin 500mg no prescription
prednisone without rx: cheap prednisone – 1 mg prednisone cost
Women who studied law, economics or medication earned over £250,000 more throughout their profession than if they had not acquired a level.
For those who already get an element for managed migration or an SDP, your Universal Credit score cost may not go up by the whole amount of the LCWRA component.
We purchased her an illustrated dinosaur e book that explains loss of life to youngsters in a secular way.
The song had been used to mark the exit of contestants as they had been voted off the present.
On June 21, 2011, the hospital introduced that its name was altering from The Youngsters’s Hospital to Children’s Hospital Colorado.
Only downside? Neither of you should have the satisfying joy of saying “checkmate” out loud on your opponent to listen to.
Официальная покупка диплома вуза с сокращенной программой обучения в Москве
simple-com.ru/forum/user/2080/
Lilian Bernice Lynch, British topic resident in France.
In addition, the two named councils, and more, accumulate meals waste together with garden waste, by sending out kitchen caddies and compostable bin liners.
Можно ли купить аттестат о среднем образовании? Основные рекомендации
The collection is ready in Memphis, Tennessee and follows Elijiah Straight (Smits) and his daughter Sydney (McGee), each of whom work at a law agency that specializes in dealing with civil rights instances, lots of that are thought of controversial.
MH and VHO reserving the traditional fluorescents for “least demanding animals in shallow aquaria 40 cm or much less in depth”.
Hi! 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 useful information to work on. You have done a outstanding job!
界面新闻.新浪新闻.