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

37,669 Responses

  1. MalcolmmiB表示:

    фильм качестве бесплатно фильмы в 4К бесплатно онлайн

  2. Peterclada表示:

    kamagra pas cher Kamagra Oral Jelly pas cher Kamagra Oral Jelly pas cher

  3. Peterclada表示:

    acheter mГ©dicament en ligne sans ordonnance pharmacie en ligne pharmacie en ligne avec ordonnance pharmafst.shop

  4. Bernardshoor表示:

    Achetez vos kamagra medicaments: Kamagra pharmacie en ligne – kamagra livraison 24h

  5. Robertfap表示:

    http://pharmafst.com/# pharmacie en ligne avec ordonnance

  6. Peterclada表示:

    Acheter Cialis Pharmacie en ligne Cialis sans ordonnance cialis sans ordonnance tadalmed.com

  7. BradleyJaire表示:

    Kamagra pharmacie en ligne: kamagra 100mg prix – kamagra gel

  8. Your website doesn’t show up correctly on my iphone4 – you might wanna try and repair that

  9. BillieLet表示:

    Tadalafil sans ordonnance en ligne: Cialis sans ordonnance 24h – cialis sans ordonnance tadalmed.shop

  10. Robertfap表示:

    https://pharmafst.shop/# pharmacie en ligne sans ordonnance

  11. Appreciating the commitment you put into your website and in depth information you provide. It’s great to come across a blog every once in a while that isn’t the same outdated rehashed information. Great read! I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

  12. You can definitely see your expertise in the paintings you write. The world hopes for even more passionate writers such as you who are not afraid to mention how they believe. Always follow your heart.

  13. Thanks for giving your ideas. The one thing is that learners have a solution between federal government student loan and also a private education loan where it can be easier to go with student loan debt consolidation than with the federal education loan.

  14. BillieLet表示:

    pharmacie en ligne livraison europe: Livraison rapide – pharmacie en ligne france livraison belgique pharmafst.com

  15. Peterclada表示:

    Tadalafil 20 mg prix en pharmacie Acheter Cialis 20 mg pas cher Tadalafil sans ordonnance en ligne tadalmed.com

  16. Bernardshoor表示:

    Kamagra Commander maintenant: kamagra livraison 24h – Kamagra pharmacie en ligne

  17. Bernardshoor表示:

    cialis sans ordonnance: Pharmacie en ligne Cialis sans ordonnance – Cialis sans ordonnance pas cher tadalmed.shop

  18. Bernardshoor表示:

    Pharmacie en ligne Cialis sans ordonnance: Pharmacie en ligne Cialis sans ordonnance – Tadalafil 20 mg prix en pharmacie tadalmed.shop

  19. Robertfap表示:

    https://kamagraprix.com/# Kamagra pharmacie en ligne

  20. BradleyJaire表示:

    cialis sans ordonnance: cialis prix – Acheter Cialis tadalmed.shop

  21. There are certainly a whole lot of details like that to take into consideration. That may be a nice point to carry up. I provide the ideas above as normal inspiration but clearly there are questions like the one you carry up where the most important thing might be working in trustworthy good faith. I don?t know if best practices have emerged round things like that, but I am certain that your job is clearly recognized as a good game. Both boys and girls really feel the impression of just a second?s pleasure, for the rest of their lives.

  22. I?m now not positive where you’re getting your information, however great topic. I must spend a while learning more or understanding more. Thank you for wonderful info I used to be looking for this info for my mission.

  23. Идеальные жалюзи с пультом для любой комнаты
    жалюзи с пультом жалюзи с пультом . Прокарниз

  24. BradleyJaire表示:

    pharmacie en ligne livraison europe: Meilleure pharmacie en ligne – pharmacie en ligne fiable pharmafst.com

  25. Robertfap表示:

    https://tadalmed.shop/# Tadalafil 20 mg prix en pharmacie

  26. I’m truly enjoying the design and layout of your blog. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a developer to create your theme? Great work!

  27. I am really loving the theme/design of your site. Do you ever run into any web browser compatibility problems? A couple of my blog visitors have complained about my blog not operating correctly in Explorer but looks great in Chrome. Do you have any tips to help fix this problem?

  28. BillieLet表示:

    acheter mГ©dicament en ligne sans ordonnance: pharmacie en ligne – pharmacie en ligne avec ordonnance pharmafst.com

發佈留言

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