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 } }
slot siteleri: slot oyunlar? – az parayla cok kazandiran slot oyunlar?
Thanks for another wonderful article. Where else could anyone get that type of information in such a perfect way of writing? I’ve a presentation next week, and I am on the look for such information.
deneme bonusu veren casino siteleri: Canl? Casino Siteleri – Deneme Bonusu Veren Siteler
slot oyunlar?: slot oyunlar? – slot oyunlar? puf noktalar?
https://slotsiteleri25.com/# guvenilir slot siteleri
stamp online maker free stamp online maker free .
deneme bonusu veren siteler yeni deneme bonusu veren siteler yeni deneme bonusu veren yeni siteler
I?d have to verify with you here. Which isn’t something I usually do! I get pleasure from reading a post that will make folks think. Additionally, thanks for allowing me to comment!
поддельный диплом купить
https://casinositeleri25.com/# Casino Siteleri
en kazancl? slot oyunlar? slot oyunlar? puf noktalar? slot oyunlar?
sweet bonanza oyna: sweet bonanza demo oyna – sweet bonanza yorumlar
http://www.airlines-inform.ru/personal/user/?UID=73969 [url=www.ya.5bb.ru/viewtopic.php?id=22973#p67696]www.ya.5bb.ru/viewtopic.php?id=22973#p67696[/url] .
Thanks for the distinct tips shared on this website. I have noticed that many insurance providers offer clients generous special discounts if they elect to insure a couple of cars with them. A significant quantity of households have got several autos these days, specially those with more mature teenage children still dwelling at home, plus the savings with policies may soon begin. So it is good to look for a great deal.
stamp maker online stamp maker online .
Как купить аттестат 11 класса с официальным упрощенным обучением в Москве
http://denemebonusuverensiteler25.com/# yeni deneme bonusu veren siteler
make a stamp online make a stamp online .
Thank you, I have recently been searching for info about this subject for ages and yours is the best I have located so far.
create stamp online free [url=http://www.stamp-creator-online0.com]create stamp online free[/url] .
купить диплом педагогический
free stamp maker online https://www.stamp-creator-online0.com .
Внимание, игроки!
Желаете окунуться в пространство онлайн-игр и получить настоящие средства? Тогда вам к нам! Топ лучших отличных игровых сайтов 2025
Наш тг-профиль — ваш проводник в пространство отличных интернет-казино в Российской Федерации! Мы подобрали ТОП-10 безопасных казино, где вы сумеете играть на деньги и вывести свои доходы без трудностей.
Что вас ждет:
Честные отзывы и ранги казино онлайн на реальные деньги рейтинг лучших от действительных геймеров. Хорошая репутация любого ресурса подтверждена временем и клиентами. Безоплатная регистрация и мгновенный вход на любой площадках. Активные дубликаты для доступа к вашему любимому игровой площадке в каждый час. Мобильная софт для легкой развлечения так угодно.
Почему мы?
Надежные и проверенные казино с превосходными условиями для проведения времени. Гарантия ваших сведений и операций обеспечена. Новые новости и события мира виртуальных-игр в России.
I have learned some new items from your site about personal computers. Another thing I have always assumed is that computer systems have become something that each house must have for some reasons. They offer convenient ways in which to organize the home, pay bills, shop, study, listen to music and perhaps watch tv shows. An innovative strategy to complete all of these tasks is by using a notebook computer. These pcs are mobile ones, small, highly effective and mobile.
sweet bonanza giris sweet bonanza kazanma saatleri sweet bonanza giris
Just like the excessive stage Foxes, those chosen to be in the military are normally picked from start and have by no means once met their mother and father.
Strategic match expresses the degree to which a corporation is matching its sources and capabilities with the opportunities within the exterior surroundings.