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

16,482 Responses

  1. BrandenSlomy表示:

    max pharm: buy priligy max pharm – priligy max pharm

  2. StevenNub表示:

    priligy: buy dapoxetine online – priligy maxpharm

  3. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why waste your intelligence on just posting videos to your blog when you could be giving us something informative to read?

  4. робокасса промокоды http://promokod-robokassa.ru .

  5. Danieljek表示:

    buy amoxicillin online with paypal https://priligymaxpharm.com/# buy dapoxetine online

  6. StevenNub表示:

    purchase prednisone no prescription: prednisone daily use – prednisone pills for sale

  7. робокасса промокод скидка на подключение робокасса промокод скидка на подключение .

  8. gay sex表示:

    hi!,I like your writing very much! share we communicate more about your article on AOL? I need an expert on this area to solve my problem. May be that’s you! Looking forward to see you.

  9. bpdb.gov.bd表示:

    I have noticed that car insurance businesses know the motors which are susceptible to accidents and also other risks. They also know what sort of cars are prone to higher risk as well as the higher risk they have got the higher the premium rate. Understanding the basic basics regarding car insurance will let you choose the right type of insurance policy that can take care of the needs you have in case you get involved in an accident. Many thanks sharing the particular ideas on your blog.

  10. Dereketerm表示:

    prednisone 21 pack: ray pharm – 20mg prednisone

  11. Узнай все о варикоцеле левого яичка варикоцеле диагностика

  12. Dereketerm表示:

    buy amoxicillin 250mg: Amoxicillin Com Pharm – amoxicillin in india

  13. Dereketerm表示:

    priligy: buy priligy – priligy maxpharm

  14. gay sex表示:

    Yet another thing is that while looking for a good on the net electronics retail outlet, look for online stores that are continuously updated, maintaining up-to-date with the most recent products, the top deals, and helpful information on products. This will make certain you are doing business with a shop that really stays over the competition and give you what you should need to make intelligent, well-informed electronics acquisitions. Thanks for the important tips I have really learned from your blog.

  15. Many thanks for this article. I’d personally also like to say that it can end up being hard when you find yourself in school and just starting out to initiate a long credit history. There are many college students who are simply trying to survive and have long or favourable credit history can be a difficult matter to have.

  16. Узнай все о чем опасно варикоцеле степени варикоцеле

  17. bpdb.gov.bd表示:

    Yet another issue is that video games are generally serious naturally with the key focus on learning rather than enjoyment. Although, we have an entertainment factor to keep your young ones engaged, each one game is normally designed to focus on a specific group of skills or programs, such as mathmatical or scientific discipline. Thanks for your posting.

  18. bpdb.gov.bd表示:

    One thing I would really like to say is always that before buying more computer memory, look into the machine in to which it can be installed. In the event the machine can be running Windows XP, for instance, the actual memory limit is 3.25GB. Setting up above this would easily constitute just a waste. Make certain that one’s motherboard can handle the particular upgrade volume, as well. Great blog post.

  19. bpdb.gov.bd表示:

    You really make it appear really easy together with your presentation but I find this matter to be actually something which I believe I might never understand. It seems too complicated and extremely wide for me. I’m looking ahead for your subsequent submit, I?ll attempt to get the hold of it!

  20. online casino表示:

    Nice post. I be taught one thing more challenging on different blogs everyday. It’s going to all the time be stimulating to read content material from different writers and apply a little something from their store. I?d desire to make use of some with the content on my weblog whether you don?t mind. Natually I?ll provide you with a link in your net blog. Thanks for sharing.

  21. Bradleygoath表示:

    prednisone buy cheap prednisoneraypharm prednisone for sale online

  22. StevenNub表示:

    buy priligy: cheap priligy – buy priligy max pharm

  23. bpdb.gov.bd表示:

    I’ve noticed that credit restoration activity has to be conducted with techniques. If not, it’s possible you’ll find yourself damaging your ranking. In order to succeed in fixing your credit history you have to see to it that from this second you pay all your monthly expenses promptly in advance of their slated date. It is really significant given that by certainly not accomplishing so, all other measures that you will choose to adopt to improve your credit position will not be helpful. Thanks for giving your suggestions.

  24. BrandenSlomy表示:

    amoxicillin online canada: Com Pharm – amoxicillin 500 coupon

  25. BrandenSlomy表示:

    dapoxetine price: buy priligy – dapoxetine price

  26. Узнай все о варикоцеле диагностика рецидив варикоцеле

發佈留言

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