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 } }
I’m amazed by the quality of this content! The author has undoubtedly put a tremendous amount of effort into exploring and arranging the information. It’s exciting to come across an article that not only offers valuable information but also keeps the readers hooked from start to finish. Hats off to her for producing such a brilliant work!
Have you ever considered creating an ebook or guest authoring on other websites? I have a blog based upon on the same ideas you discuss and would love to have you share some stories/information. I know my visitors would appreciate your work. If you are even remotely interested, feel free to shoot me an e mail.
Hello There. I found your blog using msn. This is a very well written article. I?ll be sure to bookmark it and come back to read more of your useful info. Thanks for the post. I will certainly return.
What i do not realize is in fact how you are no longer actually a lot more neatly-appreciated than you might be right now. You are so intelligent. You understand therefore significantly in the case of this subject, made me individually imagine it from a lot of various angles. Its like women and men don’t seem to be involved until it?s one thing to do with Girl gaga! Your personal stuffs excellent. At all times deal with it up!
Hi there I am so glad I found your webpage, I really found you by error, while I was browsing on Aol for something else, Anyways I am here now and would just like to say kudos for a incredible post and a all round thrilling blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up the excellent job.
Hi there, You have done a great job. I will definitely digg it and personally suggest to my friends. I am sure they’ll be benefited from this website.
Pretty component to content. I just stumbled upon your weblog and in accession capital to assert that I get actually loved account your weblog posts. Anyway I?ll be subscribing in your augment and even I success you access constantly rapidly.
Thanks for your fascinating article. One other problem is that mesothelioma cancer is generally brought on by the inhalation of fibres from mesothelioma, which is a dangerous material. It really is commonly viewed among workers in the engineering industry who may have long contact with asbestos. It’s also caused by residing in asbestos covered buildings for years of time, Inherited genes plays an important role, and some people are more vulnerable to the risk than others.
I was just searching for this info for a while. After six hours of continuous Googleing, finally I got it in your website. I wonder what’s the lack of Google strategy that do not rank this type of informative web sites in top of the list. Usually the top websites are full of garbage.
Great blog here! Also your web site loads up fast! What web host are you using? Can I get your affiliate link to your host? I wish my site loaded up as fast as yours lol
I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored subject matter stylish. nonetheless, you command get bought an nervousness over that you wish be delivering the following. unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this hike.
I have learn a few just right stuff here. Certainly worth bookmarking for revisiting. I surprise how so much effort you put to make this sort of magnificent informative web site.
I like what you guys are up also. Such clever work and reporting! Carry on the superb works guys I?ve incorporated you guys to my blogroll. I think it will improve the value of my site 🙂
My spouse and I absolutely love your blog and find nearly all of your post’s to be what precisely I’m looking for. Do you offer guest writers to write content for yourself? I wouldn’t mind composing a post or elaborating on a lot of the subjects you write about here. Again, awesome web log!
hey there and thank you for your info ? I have definitely picked up anything new from right here. I did however expertise several technical issues using this site, since I experienced to reload the web site many times previous to I could get it to load properly. I had been wondering if your web host is OK? Not that I am complaining, but sluggish loading instances times will very frequently affect your placement in google and could damage your quality score if ads and marketing with Adwords. Anyway I am adding this RSS to my e-mail and can look out for much more of your respective intriguing content. Make sure you update this again very soon..
Attractive section of content. I just stumbled upon your web site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Anyway I?ll be subscribing to your augment and even I achievement you access consistently fast.
What an insightful and well-researched article! The author’s meticulousness and aptitude to present intricate ideas in a understandable manner is truly admirable. I’m totally captivated by the depth of knowledge showcased in this piece. Thank you, author, for sharing your knowledge with us. This article has been a game-changer!
I just like the helpful info you supply for your articles. I?ll bookmark your blog and test again here frequently. I am quite sure I?ll be told lots of new stuff right here! Best of luck for the following!
Excellent goods from you, man. I’ve understand your stuff previous to and you are just extremely wonderful. I really like what you’ve acquired here, certainly like what you are stating and the way in which you say it. You make it entertaining and you still care for to keep it sensible. I can not wait to read much more from you. This is actually a tremendous web site.
Just wish to say your article is as surprising. The clearness in your publish is simply excellent and that i can think you’re knowledgeable in this subject. Well with your permission let me to take hold of your feed to stay updated with impending post. Thank you 1,000,000 and please carry on the rewarding work.
I’ve learned many important things via your post. I will also like to mention that there may be a situation that you will apply for a loan and do not need a co-signer such as a Government Student Aid Loan. In case you are getting a loan through a regular bank then you need to be willing to have a cosigner ready to allow you to. The lenders will base their own decision on a few variables but the greatest will be your credit score. There are some loan merchants that will in addition look at your work history and make a decision based on this but in most cases it will be based on on your score.
Do you have a spam issue on this site; I also am a blogger, and I was curious about your situation; we have created some nice practices and we are looking to trade methods with other folks, be sure to shoot me an e-mail if interested.
I am so happy to read this. This is the type of manual that needs to be given and not the random misinformation that is at the other blogs. Appreciate your sharing this best doc.
Отличный сайт! Всем рекомендую!проститутки Питера
It?s onerous to find knowledgeable individuals on this topic, but you sound like you recognize what you?re talking about! Thanks
Thanks for your blog post. I would love to say that the health insurance broker also works best for the benefit of the coordinators of the group insurance cover. The health insurance agent is given an index of benefits needed by someone or a group coordinator. Such a broker may is seek out individuals or maybe coordinators which will best fit those wants. Then he presents his ideas and if all parties agree, the broker formulates a contract between the 2 parties.
Thank you for any other informative website. Where else could I am getting that type of info written in such a perfect approach? I have a mission that I am simply now operating on, and I’ve been at the look out for such information.
My coder is trying to convince me to move to .net from PHP. I have always disliked the idea because of the expenses. But he’s tryiong none the less. I’ve been using WordPress on various websites for about a year and am concerned about switching to another platform. I have heard great things about blogengine.net. Is there a way I can transfer all my wordpress content into it? Any help would be greatly appreciated!
Good day! This post could not be written any better! Reading this post reminds me of my previous room mate! He always kept chatting about this. I will forward this write-up to him. Fairly certain he will have a good read. Many thanks for sharing!
An fascinating discussion is value comment. I think that it is best to write more on this matter, it might not be a taboo topic however generally people are not enough to talk on such topics. To the next. Cheers