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
    }
}

You may also like...

10,530 Responses

  1. My partner and I stumbled over here coming from a different web page and thought I may as well check things out. I like what I see so now i’m following you. Look forward to looking into your web page for a second time.

  2. Itamar Medical Ltd. ITMR 944 0.21 Medical Equipment Development & commercialization of non-invasive medical devices.

  3. Currently, the market is estimated at INR 14.6 bn and is anticipated to attain a CAGR of 61 to reach INR 98.9 bn by 2015.

  4. Its expansionism spurred several wars that produced at least two sovereign nations.

  5. Treflqp表示:

    Здравствуйте!
    Как приобрести аттестат о среднем образовании в Москве и других городах
    beloglovskaya.blogspot.com/2018/04/yves-rocher-elixir-jeunesse
    Поможем вам всегда!.

  6. 信 音読み表示:

    These accidents should at all times have an look of reality.

  7. Great write-up, I?m regular visitor of one?s site, maintain up the nice operate, and It is going to be a regular visitor for a lengthy time.

  8. I have fun with, lead to I found just what I used to be having a look for. You have ended my 4 day lengthy hunt! God Bless you man. Have a great day. Bye

  9. I?ve read some good stuff here. Certainly worth bookmarking for revisiting. I surprise how so much attempt you put to make this type of fantastic informative web site.

  10. Furthermore, i believe that mesothelioma cancer is a uncommon form of cancer malignancy that is typically found in people previously familiar with asbestos. Cancerous cells form while in the mesothelium, which is a shielding lining which covers a lot of the body’s internal organs. These cells commonly form in the lining with the lungs, stomach, or the sac that really encircles the heart. Thanks for discussing your ideas.

  11. Great post. I was checking continuously this blog and I am impressed! Extremely helpful info specifically the final phase 🙂 I handle such info much. I was seeking this particular info for a long time. Thank you and good luck.

  12. Thanks for your article. I would like to say that the very first thing you will need to carry out is to see if you really need credit repair. To do that you have got to get your hands on a replica of your credit file. That should not be difficult, because the government necessitates that you are allowed to get one free of charge copy of your actual credit report annually. You just have to inquire the right men and women. You can either check out the website owned by the Federal Trade Commission or contact one of the major credit agencies immediately.

  13. How to Enter into Profitable IPO Stock Trading?

  14. I was suggested this web site by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my difficulty. You’re incredible! Thanks!

  15. Suncor Energy reported 2019 revenues of CAN$39.Eight billion.

  16. Can I just say what a aid to search out somebody who truly is aware of what theyre talking about on the internet. You positively know the right way to carry an issue to gentle and make it important. Extra individuals have to learn this and perceive this side of the story. I cant consider youre no more popular because you definitely have the gift.

  17. In addition, SMEs are not always able to cope with the different standards deriving from European and International law such as for instance, the International Financial Reporting Standards (IFRS), generating extra costs for SMEs and undermining their credibility vis-脿-vis possible investors that look for transparency and guarantees of good management.

  18. I have noticed that online diploma is getting preferred because obtaining your degree online has become a popular solution for many people. Numerous people have not had a possibility to attend a regular college or university nonetheless seek the improved earning possibilities and a better job that a Bachelor’s Degree grants. Still other individuals might have a qualification in one discipline but would choose to pursue something they now possess an interest in.

  19. Good ? I should definitely pronounce, impressed with your web site. I had no trouble navigating through all tabs as well as related info ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or something, web site theme . a tones way for your customer to communicate. Excellent task..

  20. Definitely believe that that you said. Your favorite reason appeared to be on the internet the simplest factor to be mindful of. I say to you, I definitely get irked while other people consider worries that they plainly do not realize about. You managed to hit the nail upon the highest and also outlined out the entire thing with no need side effect , people can take a signal. Will likely be again to get more. Thank you

  21. Lynch reports that from his early teens he labored as a caddie to assist help the family.

  22. Very nice post. I just stumbled upon your weblog and wanted to say that I have truly enjoyed surfing around your blog posts. After all I?ll be subscribing to your rss feed and I hope you write again very soon!

  23. The crux of your writing whilst sounding agreeable initially, did not settle properly with me personally after some time. Somewhere throughout the paragraphs you actually managed to make me a believer unfortunately only for a while. I however have a problem with your jumps in assumptions and one might do nicely to help fill in all those gaps. In the event you actually can accomplish that, I could certainly be amazed.

  24. Many thanks for your post. I’d like to write my opinion that the tariff of car insurance varies from one policy to another, since there are so many different facets which play a role in the overall cost. By way of example, the make and model of the car or truck will have an enormous bearing on the cost. A reliable outdated family automobile will have a more affordable premium than just a flashy sports vehicle.

  25. khawfang vk表示:

    Woah! I’m really loving the template/theme of this website. It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between superb usability and appearance. I must say that you’ve done a amazing job with this. Additionally, the blog loads super quick for me on Safari. Excellent Blog!

  26. I’m not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your site to come back in the future. Cheers

  27. There are some attention-grabbing time limits on this article however I don?t know if I see all of them middle to heart. There’s some validity however I’ll take maintain opinion until I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as properly

  28. Thank you for another magnificent post. Where else could anyone get that kind of info in such a perfect way of writing? I have a presentation next week, and I am on the look for such info.

  29. Great beat ! I would like to apprentice while you amend your site, how can i subscribe for a blog web site? The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear idea

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。