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 } }
Get More Information https://toastwallet.org
Этот информативный текст сочетает в себе темы здоровья и зависимости. Мы обсудим, как хронические заболевания могут усугубить зависимости и наоборот, как зависимость может влиять на общее состояние здоровья. Читатели получат представление о комплексном подходе к лечению как физического, так и психического состояния.
Получить больше информации – https://mednarkoforum.ru/
A place where customer health is the top priority.
https://cytotecpharm24.top/
Their global reach is unmatched.
I appreciate the range of payment options they offer.
order cheap cipro without dr prescription
Their international supply chain ensures no medication shortages.
Some trends of drugs.
how to buy clomid online
A beacon of excellence in pharmaceutical care.
Their global perspective enriches local patient care.
can you get cheap clomid tablets
Their 24/7 support line is super helpful.
Hi! I know this is kinda off topic however I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa? My blog discusses a lot of the same subjects as yours and I feel we could greatly benefit from each other. If you might be interested feel free to send me an e-mail. I look forward to hearing from you! Superb blog by the way!
Hassle-free prescription transfers every time.
where to buy lisinopril 20mg online
Making global healthcare accessible and affordable.
1win скачать kg 1win скачать kg .
wonderful issues altogether, you just received a emblem new reader. What may you suggest in regards to your put up that you simply made a few days in the past? Any positive?
useful source https://toastwallet.org/
additional info https://toastwallet.org/
site https://web-martianwallet.io/
1win. https://1win110.com.kg/ .
weblink https://toastwallet.org/
Always professional, whether dealing domestically or internationally.
cost of cheap clomid pills
They provide a global perspective on local health issues.
I think one of your commercials caused my web browser to resize, you may well want to put that on your blacklist.
В этой статье обсуждаются актуальные медицинские вопросы, которые волнуют общество. Мы обращаем внимание на проблемы, касающиеся здравоохранения и лечения, а также на новшества в области медицины. Читатели будут осведомлены о последних событиях и смогут следить за тенденциями в медицине.
Выяснить больше – https://mednarkoforum.ru/
Have you ever considered about including a little bit more than just your articles? I mean, what you say is important and everything. However think of if you added some great graphics or video clips to give your posts more, “pop”! Your content is excellent but with pics and clips, this blog could certainly be one of the greatest in its niche. Terrific blog!
safe canadian pharmacies online
I am not sure where you are getting your information, but great topic. I needs to spend some time learning more or understanding more. Thanks for fantastic info I was looking for this info for my mission.
A reliable pharmacy in times of emergencies.
https://cipropharm24.top/
They have an impressive roster of international certifications.
visit homepage https://web-martianwallet.io
Prescription Drug Information, Interactions & Side.
https://gabapentinpharm24.top/
Love the seasonal health tips they offer.
I found your weblog website on google and examine a few of your early posts. Proceed to keep up the very good operate. I just further up your RSS feed to my MSN News Reader. In search of forward to reading more from you afterward!?
1win зайти 1win зайти .
They keep a broad spectrum of rare medications.
gabapentin veterinary dogs
Global reach with a touch of personal care.
I?ve been exploring for a little for any high-quality articles or weblog posts on this kind of house . Exploring in Yahoo I at last stumbled upon this website. Studying this information So i am glad to exhibit that I have a very excellent uncanny feeling I discovered exactly what I needed. I such a lot without a doubt will make sure to don?t fail to remember this site and provides it a look on a continuing basis.
1вин кг http://1win103.com.kg/ .
Get here.
xylitol in gabapentin
Their home delivery service is top-notch.