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 } }
Быстрая схема покупки диплома старого образца: что важно знать?
odessamama.net/forum.php?mod=viewthread&tid=298208&extra=
Парадокс, но купить диплом кандидата наук оказалось не так и сложно
I absolutely love your blog and find almost all of your post’s to be just what I’m looking for. can you offer guest writers to write content for you personally? I wouldn’t mind composing a post or elaborating on many of the subjects you write about here. Again, awesome weblog!
Hey There. I found your weblog the use of msn. This is a really neatly written article. I?ll make sure to bookmark it and return to learn extra of your useful info. Thanks for the post. I will definitely comeback.
In my opinion that a foreclosed can have a important effect on the client’s life. House foreclosures can have a Six to a decade negative effects on a client’s credit report. A borrower that has applied for home financing or almost any loans even, knows that the actual worse credit rating is actually, the more challenging it is for any decent mortgage. In addition, it may affect a new borrower’s chance to find a decent place to lease or hire, if that gets the alternative houses solution. Good blog post.
Today, I went to the beach with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!
вывод из запоя ростов-на-дону http://www.business.0pk.me/viewtopic.php?id=37942#p224618/ .
анонимный вывод из запоя ростов https://www.alhambra.bestforums.org/viewtopic.php?f=2&t=46349 .
https://canadiandrugsgate.com/# best non prescription ed pills
Тут можно преобрести сейф огнестойкий в москве сейф несгораемый купить
Легальная покупка диплома ПТУ с сокращенной программой обучения
calc-bank.ru/diplom-vo-kupit.html
hi!,I like your writing very much! proportion we keep up a correspondence extra approximately your post on AOL? I require a specialist on this house to solve my problem. Maybe that’s you! Having a look ahead to peer you.
Thanks for your post. One other thing is that individual states in the United states of america have their own laws that will affect home owners, which makes it very difficult for the the legislature to come up with a new set of recommendations concerning property foreclosures on house owners. The problem is that every state provides own regulations which may have interaction in an unfavorable manner in regards to foreclosure guidelines.
Thanks for the write-up. My partner and i have constantly observed that a majority of people are wanting to lose weight because they wish to show up slim plus attractive. Nonetheless, they do not often realize that there are additional benefits for losing weight in addition. Doctors state that over weight people are afflicted by a variety of conditions that can be instantly attributed to their own excess weight. Thankfully that people who sadly are overweight as well as suffering from a variety of diseases can help to eliminate the severity of their particular illnesses by simply losing weight. It is easy to see a steady but marked improvement with health as soon as even a moderate amount of weight-loss is accomplished.
Тут можно преобрести огнестойкие сейфы цена сейфы огнестойкие
hi!,I like your writing very a lot! share we be in contact more about your post on AOL? I need an expert on this house to resolve my problem. Maybe that’s you! Having a look forward to see you.
I really appreciate this post. I?ve been looking everywhere for this! Thank goodness I found it on Bing. You have made my day! Thanks again
Thanks for your useful article. Other thing is that mesothelioma cancer is generally caused by the inhalation of material from asbestos fiber, which is a carcinogenic material. It is commonly noticed among workers in the structure industry with long experience of asbestos. It can be caused by moving into asbestos protected buildings for a long period of time, Genes plays a crucial role, and some individuals are more vulnerable towards the risk as compared with others.
продамус промокоды http://prodamus-promokod21.ru .
Как получить диплом техникума с упрощенным обучением в Москве официально
It?s actually a nice and helpful piece of info. I am glad that you shared this helpful info with us. Please keep us up to date like this. Thanks for sharing.
Пошаговая инструкция по безопасной покупке диплома о высшем образовании
xn—–6kcaikgh5b6abibbeabybilsv8h6f.xn--p1ai/kupit-attestat-za-9-klass-2014.html
One thing I would really like to say is the fact before acquiring more laptop or computer memory, take a look at the machine within which it can be installed. Should the machine will be running Windows XP, for instance, a memory threshold is 3.25GB. Putting in greater than this would easily constitute some sort of waste. Make certain that one’s motherboard can handle the particular upgrade quantity, as well. Good blog post.
It is perfect time to make some plans for the future and it’s time to be happy. I have learn this submit and if I may I wish to recommend you few attention-grabbing issues or suggestions. Maybe you can write subsequent articles relating to this article. I desire to read more issues approximately it!
I would also love to add that if you do not now have an insurance policy or you do not participate in any group insurance, you may well gain from seeking the assistance of a health insurance professional. Self-employed or people with medical conditions normally seek the help of one health insurance brokerage. Thanks for your short article.
It’s the best time to make a few plans for the long run and it is time to be happy. I’ve read this publish and if I could I desire to counsel you some interesting issues or suggestions. Maybe you can write next articles referring to this article. I want to read even more issues approximately it!
It is indeed my belief that mesothelioma is usually the most lethal cancer. It contains unusual traits. The more I look at it the more I am sure it does not behave like a true solid flesh cancer. In the event that mesothelioma is often a rogue virus-like infection, then there is the chance for developing a vaccine and also offering vaccination to asbestos exposed people who are vulnerable to high risk connected with developing future asbestos associated malignancies. Thanks for revealing your ideas on this important health issue.
Nice blog right here! Additionally your web site lots up very fast! What host are you using? Can I get your associate hyperlink in your host? I wish my web site loaded up as fast as yours lol
online pharmacy india: Online medicine home delivery – cheapest online pharmacy india
There are actually numerous particulars like that to take into consideration. That could be a nice point to convey up. I supply the ideas above as general inspiration however clearly there are questions like the one you carry up the place a very powerful thing can be working in trustworthy good faith. I don?t know if greatest practices have emerged around things like that, but I’m certain that your job is clearly identified as a good game. Each boys and girls really feel the impression of only a moment?s pleasure, for the remainder of their lives.