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 } }
вывод из запоя ростов и область http://www.severussnape.borda.ru/?1-4-0-00000313-000-0-0-1730648539/ .
What i don’t understood is actually how you are not actually a lot more smartly-appreciated than you may be now. You are very intelligent. You know thus significantly in terms of this topic, produced me individually imagine it from numerous various angles. Its like women and men aren’t involved unless it is something to accomplish with Girl gaga! Your individual stuffs outstanding. Always deal with it up!
Thanks for this glorious article. One other thing is that many digital cameras come equipped with the zoom lens that permits more or less of your scene being included by means of ‘zooming’ in and out. These kind of changes in {focus|focusing|concentration|target|the a**** length will be reflected within the viewfinder and on significant display screen on the back of the particular camera.
I have observed that in the world today, video games are the latest trend with kids of all ages. There are times when it may be difficult to drag your son or daughter away from the video games. If you want the very best of both worlds, there are plenty of educational games for kids. Good post.
There are some attention-grabbing cut-off dates in this article however I don?t know if I see all of them center to heart. There’s some validity however I’ll take maintain opinion until I look into it further. Good article , thanks and we want extra! Added to FeedBurner as properly
Most of what you assert is astonishingly precise and it makes me ponder why I hadn’t looked at this with this light before. Your piece truly did switch the light on for me personally as far as this specific subject matter goes. Nevertheless there is actually one particular issue I am not really too cozy with so whilst I try to reconcile that with the core theme of the issue, allow me see exactly what the rest of the subscribers have to say.Well done.
Thanks for your write-up. One other thing is that if you are disposing your property on your own, one of the troubles you need to be aware about upfront is how to deal with household inspection reports. As a FSBO owner, the key about successfully moving your property along with saving money upon real estate agent commission rates is knowledge. The more you realize, the simpler your home sales effort will be. One area in which this is particularly important is home inspections.
Приобретение школьного аттестата с официальным упрощенным обучением в Москве
Тут можно преобрести сейф огнестойкий купить сейф пожаростойкий
Тут можно преобрести сейф противопожарный несгораемый сейф
Mostbet o‘yinchilari uchun yuqori koeffitsiyentlar va tez to‘lovlar | Mostbet orqali katta g‘alabalar yo‘lida boshlang | Mostbet orqali har kuni yangi aksiyalar va bonuslar | Mostbet bilan yuqori koeffitsiyentlar va katta yutuqlar oling | Mostbet-da yangi o‘yinlarni sinab ko‘ring va katta yutuqlar qo‘lga kiriting mostbetazcasino.com.az
Как избежать рисков при покупке диплома колледжа или ПТУ в России
Реально ли приобрести диплом стоматолога? Основные этапы
p33340zg.beget.tech/2024/10/15/oformlenie-diploma-vash-klyuch-k-uspeshnoy-karere.html
вывод из запоя на дому ростов недорого https://belbeer.borda.ru/?1-6-0-00000746-000-0-0-1730649271/ .
https://indianpharmacyeasy.com/# best india pharmacy
вывод из запоя на дому ростов на дону [url=dubna.myqip.ru/?1-5-0-00000280-000-0-0-1730649298]dubna.myqip.ru/?1-5-0-00000280-000-0-0-1730649298[/url] .
Всё, что нужно знать о покупке аттестата о среднем образовании без рисков
Полезная информация как купить диплом о высшем образовании без рисков
анонимный. вывод. из. запоя. ростов. https://cah.forum24.ru/?1-19-0-00000455-000-0-0-1730648785 .
вывод из запоя в ростове вывод из запоя в ростове .
наркология вывод из запоя ростов наркология вывод из запоя ростов .
Реально ли приобрести диплом стоматолога? Основные шаги
онлайн казино онлайн казино .
вывод из запоя дешево ростов-на-дону [url=https://gaslo.ukrbb.net/viewtopic.php?f=13&t=3409/]https://gaslo.ukrbb.net/viewtopic.php?f=13&t=3409/[/url] .
вывод из запоя на дому ростов на дону [url=www.automobilist.forum24.ru/?1-19-0-00000135-000-0-0-1730648713]www.automobilist.forum24.ru/?1-19-0-00000135-000-0-0-1730648713[/url] .
онлайн казино [url=https://www.online-kazino.by]онлайн казино[/url] .
Пошаговая инструкция по официальной покупке диплома о высшем образовании
вывод из запоя дешево ростов на дону https://aqvakr.forum24.ru/?1-7-0-00011570-000-0-0-1730648582/ .
онлайн казино онлайн казино .
вывод из запоя в стационаре ростов-на-дону http://www.family2.quadrobb.me/viewtopic.php?id=1837 .