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

15,684 Responses

  1. I have read a few good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to make such a fantastic informative website.

  2. I do trust all of the ideas you’ve presented for your post. They’re very convincing and will definitely work. Still, the posts are very brief for newbies. May you please prolong them a little from subsequent time? Thank you for the post.

  3. Hey There. I found your weblog using msn. That is a very smartly written article. I?ll be sure to bookmark it and return to read extra of your helpful information. Thank you for the post. I?ll certainly return.

  4. I loved as much as you will receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly a lot often inside case you shield this increase.

  5. I just could not leave your site prior to suggesting that I actually loved the usual info a person supply for your guests? Is going to be again incessantly in order to check out new posts

  6. praewasian表示:

    One thing I would really like to say is always that before obtaining more pc memory, take a look at the machine in to which it will be installed. If the machine can be running Windows XP, for instance, the memory threshold is 3.25GB. Setting up greater than this would just constitute a waste. Be sure that one’s mother board can handle an upgrade volume, as well. Good blog post.

  7. Hey There. I found your blog using msn. This is an extremely well written article. I will be sure to bookmark it and come back to read more of your useful information. Thanks for the post. I will certainly comeback.

  8. Good website! I truly love how it is simple on my eyes and the data are well written. I am wondering how I could be notified whenever a new post has been made. I’ve subscribed to your feed which must do the trick! Have a great day!

  9. I beloved as much as you will obtain performed proper here. The comic strip is tasteful, your authored material stylish. nevertheless, you command get bought an nervousness over that you wish be delivering the following. sick definitely come more formerly again since exactly the same just about very regularly inside of case you defend this increase.

  10. A few things i have observed in terms of computer system memory is always that there are specific features such as SDRAM, DDR etc, that must go with the specifications of the motherboard. If the personal computer’s motherboard is pretty current while there are no os issues, upgrading the memory literally will take under one hour. It’s among the easiest personal computer upgrade methods one can consider. Thanks for expressing your ideas.

  11. Thanks for this wonderful article. One other thing is that most digital cameras can come equipped with a new zoom lens that enables more or less of a scene to become included simply by ‘zooming’ in and out. These kinds of changes in {focus|focusing|concentration|target|the a**** length are reflected inside the viewfinder and on huge display screen on the back of the specific camera.

  12. This website can be a stroll-by way of for all the information you needed about this and didn?t know who to ask. Glimpse right here, and also you?ll undoubtedly discover it.

  13. Rev. Duncan established the small bank with the intention to encourage his working class congregation to develop thrift.

  14. I have recently started a site, the info you offer on this site has helped me greatly. Thank you for all of your time & work.

  15. Lazrcna表示:

    Привет, друзья!
    Мы готовы предложить дипломы психологов, юристов, экономистов и любых других профессий по приятным тарифам.
    shop.mau.ru/goods/stiker3.php

  16. Generally I do not read post on blogs, but I wish to say that this write-up very forced me to try and do so! Your writing style has been surprised me. Thanks, very nice article.

  17. I believe that avoiding packaged foods is a first step to help lose weight. They can taste beneficial, but prepared foods currently have very little nutritional value, making you eat more in order to have enough electricity to get through the day. Should you be constantly feeding on these foods, transferring to whole grain products and other complex carbohydrates will assist you to have more vitality while ingesting less. Great blog post.

  18. I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to construct my own blog and would like to find out where u got this from. many thanks

  19. Thanks for the useful information on credit repair on this web-site. A few things i would advice people should be to give up this mentality they will buy at this point and fork out later. As being a society we all tend to make this happen for many things. This includes trips, furniture, and also items we wish. However, you’ll want to separate your own wants out of the needs. When you are working to fix your credit score actually you need some trade-offs. For example it is possible to shop online to save cash or you can go to second hand stores instead of expensive department stores with regard to clothing.

  20. I think this is among the so much vital info for me. And i’m satisfied studying your article. But wanna remark on some basic things, The site taste is wonderful, the articles is truly excellent : D. Excellent task, cheers

  21. I have seen lots of useful issues on your web-site about desktops. However, I have got the judgment that notebooks are still more or less not powerful adequately to be a wise decision if you generally do jobs that require loads of power, including video touch-ups. But for web surfing, word processing, and many other typical computer work they are just fine, provided you can’t mind small screen size. Thank you sharing your opinions.

  22. It is my belief that mesothelioma is actually the most fatal cancer. It contains unusual qualities. The more I actually look at it the harder I am convinced it does not act like a true solid human cancer. If perhaps mesothelioma is really a rogue viral infection, then there is the probability of developing a vaccine and offering vaccination to asbestos exposed people who are open to high risk connected with developing long run asbestos related malignancies. Thanks for revealing your ideas for this important ailment.

  23. JSTOR 1335111. Archived from the original on July 28, 2021.

  24. I’m in awe of the author’s talent to make intricate concepts understandable to readers of all backgrounds. This article is a testament to her expertise and commitment to providing helpful insights. Thank you, author, for creating such an compelling and illuminating piece. It has been an unforgettable experience to read!

  25. けが 保険表示:

    The rebellion that Johnson cited had turned out to be only hearsay and resulted in the homicide of an innocent man.

  26. Thanks for the diverse tips provided on this blog. I have observed that many insurance companies offer customers generous discount rates if they favor to insure a couple of cars together. A significant volume of households currently have several motor vehicles these days, specially those with elderly teenage young children still living at home, as well as the savings for policies can soon increase. So it will pay to look for a good deal.

  27. Hmm it seems like your site ate my first comment (it was super long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog. I too am an aspiring blog writer but I’m still new to the whole thing. Do you have any recommendations for inexperienced blog writers? I’d really appreciate it.

  28. Oh my goodness! I’m in awe of the author’s writing skills and talent to convey intricate concepts in a concise and concise manner. This article is a real treasure that deserves all the accolades it can get. Thank you so much, author, for sharing your knowledge and providing us with such a precious asset. I’m truly appreciative!

  29. kanyabunloed表示:

    Hey very cool blog!! Man .. Beautiful .. Amazing .. I will bookmark your website and take the feeds also?I’m happy to find so many useful information here in the post, we need develop more techniques in this regard, thanks for sharing. . . . . .

  30. I do trust all of the concepts you have presented to your post. They are very convincing and can certainly work. Still, the posts are very quick for beginners. May you please extend them a little from subsequent time? Thanks for the post.

發佈留言

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