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 } }
motbet http://eisberg.forum24.ru/?1-0-0-00000327-000-0-0-1742579529/ .
Тут можно преобрести сейфы взломостойкие взломостойкий сейф
Hello there, simply became aware of your weblog via Google, and found that it is truly informative. I am gonna watch out for brussels. I?ll appreciate when you proceed this in future. Lots of other folks will be benefited from your writing. Cheers!
alo789 alo 789 dang nh?p 789alo
Thanks for the unique tips contributed on this site. I have noticed that many insurers offer buyers generous deals if they opt to insure a few cars with them. A significant volume of households currently have several cars these days, specifically those with more aged teenage youngsters still located at home, along with the savings with policies can certainly soon begin. So it is good to look for a great deal.
F*ckin? remarkable things here. I am very happy to see your post. Thank you a lot and i am looking ahead to touch you. Will you please drop me a mail?
This website is known as a stroll-through for all of the info you needed about this and didn?t know who to ask. Glimpse right here, and also you?ll undoubtedly discover it.
Thanks for the good writeup. It actually was a entertainment account it. Glance complex to far introduced agreeable from you! However, how can we keep in touch?
Excellent read, I just passed this onto a friend who was doing a little research on that. And he actually bought me lunch as I found it for him smile So let me rephrase that: Thank you for lunch!
F*ckin? amazing things here. I am very happy to see your article. Thanks a lot and i am having a look forward to contact you. Will you kindly drop me a mail?
naturally like your website but you need to check the spelling on several of your posts. A number of them are rife with spelling problems and I find it very bothersome to tell the truth nevertheless I will surely come back again.
Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but instead of that, this is magnificent blog. An excellent read. I’ll certainly be back.
Heya! I just wanted to ask if you ever have any issues with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no data backup. Do you have any methods to prevent hackers?
http://88betviet.pro/# keo nha cai 88bet
Based on my study, after a foreclosures home is available at a bidding, it is common for the borrower to be able to still have some sort ofthat remaining unpaid debt on the financial loan. There are many loan merchants who try and have all charges and liens paid by the subsequent buyer. However, depending on selected programs, polices, and state regulations there may be a number of loans that aren’t easily settled through the exchange of lending products. Therefore, the responsibility still rests on the customer that has received his or her property in foreclosure process. Many thanks sharing your opinions on this blog site.
keo nha cai 88bet nha cai 88bet 88bet slot
Thanks for revealing your ideas. I’d also like to state that video games have been at any time evolving. Technology advances and innovations have helped create practical and interactive games. These kind of entertainment games were not as sensible when the actual concept was first of all being tried out. Just like other forms of technology, video games also have had to progress via many ages. This itself is testimony for the fast continuing development of video games.
I loved your blog post.Thanks Again. Great.
Thanks a lot for the helpful article. It is also my belief that mesothelioma cancer has an extremely long latency time period, which means that signs and symptoms of the disease may well not emerge until 30 to 50 years after the first exposure to asbestos fiber. Pleural mesothelioma, which can be the most common variety and is affecting the area around the lungs, may cause shortness of breath, chest pains, along with a persistent cough, which may cause coughing up blood vessels.
Hi my loved one! I want to say that this post is awesome, great written and come with approximately all important infos. I?d like to see more posts like this .
keo nha cai 88bet 88bet 88bet
https://alo789.auction/# alo789in
Hi there very cool site!! Guy .. Excellent .. Wonderful .. I’ll bookmark your site and take the feeds additionally?I’m happy to seek out a lot of useful information here in the put up, we want develop more strategies on this regard, thank you for sharing. . . . . .
I believe this is one of the so much important information for me. And i am happy reading your article. But want to remark on some normal things, The web site style is ideal, the articles is in point of fact great : D. Just right activity, cheers
https://k8viet.guru/# k8vip
Do you have a spam issue on this site; I also am a blogger, and I was curious about your situation; we have developed some nice practices and we are looking to swap solutions with others, be sure to shoot me an email if interested.
Good web site! I truly love how it is simple on my eyes and the data are well written. I am wondering how I might be notified whenever a new post has been made. I have subscribed to your RSS which must do the trick! Have a nice day!
Тут можно преобрести сейф купить сейф купить цена
Устал терять в азартном доме? Перестань играть вслепую! Вступай на Наш Telegram канал “Рейтинг Казино”! ??
Оставь в прошлом о потерянных депозитах и крушениях надежд! Наш Telegram-канал “Наш канал” будет твоим лучшим помощником в сфере азартных игр!
Что же тебя ожидает в канале:
Беспристрастные обзоры игровых платформ: Мы анализируем всё – от разрешения и известности до бонусов и времени переводов. Совершенно никаких рекламы, только открытая информация!
Свежие списки: Выясни, которые платформы действительно переводят выигрыши и дают оптимальные требования для клиентов!
Особенные премии и промокоды: Воспользуйся наиболее прибыльные акции от надежных платформ!
Последние новости из сферы азартных игр: Будь в знании новых случаев и тенденций!
Рекомендации и тактики от бывалых пользователей: Повысь свои шансы на успех и делай ставки с рассудительностью!
Перестань надеяться на удачу! Самое время ставить осознанно!
Вступай на “Канал “Рейтинг Казино”” прямо сейчас и сделай азарт в доход!
https://t.me/s/reyting_top_kazino
Thanks for sharing your ideas listed here. The other thing is that any time a problem takes place with a computer system motherboard, people today should not take the risk involving repairing this themselves because if it is not done correctly it can lead to permanent damage to the entire laptop. It is usually safe to approach your dealer of your laptop for your repair of the motherboard. They’ve already technicians who’ve an knowledge in dealing with mobile computer motherboard problems and can make the right analysis and execute repairs.