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

38,256 Responses

  1. Curve Swap表示:

    Spot on with this write-up, I really suppose this website needs way more consideration. I?ll most likely be once more to learn way more, thanks for that info.

  2. Williecrady表示:

    Kasino menawarkan pengalaman bermain yang seru https://preman69.tech/# Pemain sering berbagi tips untuk menang

  3. ThomasThype表示:

    Slot menawarkan kesenangan yang mudah diakses: bonaslot.site – BonaSlot

  4. ThomasThype表示:

    Kasino menyediakan layanan pelanggan yang baik: garuda888 – garuda888

  5. FoxBusiness表示:

    Thanks for your helpful article. One other problem is that mesothelioma is generally a result of the inhalation of fibers from asbestos, which is a cancer causing material. It is commonly noticed among employees in the engineering industry who definitely have long exposure to asbestos. It’s also caused by living in asbestos covered buildings for a long time of time, Genetics plays a crucial role, and some people are more vulnerable towards the risk compared to others.

  6. ThomasThype表示:

    Mesin slot menawarkan pengalaman bermain yang cepat: slot demo gratis – slot demo

  7. Curve Swap表示:

    Thanks for your writing. I would also love to say that your health insurance dealer also utilizes the benefit of the particular coordinators of the group insurance coverage. The health insurance professional is given an index of benefits needed by somebody or a group coordinator. Such a broker really does is hunt for individuals as well as coordinators which often best fit those needs. Then he gifts his advice and if both parties agree, the broker formulates a contract between the 2 parties.

  8. DavidCooth表示:

    https://slotdemo.auction/# Mesin slot menawarkan pengalaman bermain yang cepat

  9. Williecrady表示:

    Slot dengan fitur interaktif semakin banyak tersedia http://preman69.tech/# Mesin slot sering diperbarui dengan game baru

  10. Aaronbus表示:

    slot 88 slot88.company Kasino memastikan keamanan para pemain dengan baik

  11. I have witnessed that smart real estate agents everywhere are Promotion. They are noticing that it’s not only placing a poster in the front area. It’s really in relation to building relationships with these traders who at some time will become consumers. So, once you give your time and energy to assisting these sellers go it alone : the “Law connected with Reciprocity” kicks in. Good blog post.

  12. ThomasThype表示:

    Banyak kasino menawarkan permainan langsung yang seru: preman69.tech – preman69.tech

  13. Aaronbus表示:

    garuda888 slot garuda888 Permainan slot bisa dimainkan dengan berbagai taruhan

  14. Williecrady表示:

    Mesin slot dapat dimainkan dalam berbagai bahasa https://slotdemo.auction/# Mesin slot sering diperbarui dengan game baru

  15. Williecrady表示:

    Slot dengan grafis 3D sangat mengesankan https://slot88.company/# Kasino menawarkan pengalaman bermain yang seru

  16. DavidCooth表示:

    https://bonaslot.site/# Permainan slot mudah dipahami dan menyenangkan

  17. DavidCooth表示:

    http://garuda888.top/# Banyak kasino menawarkan permainan langsung yang seru

  18. Aaronbus表示:

    garuda888 slot garuda888.top Mesin slot digital semakin banyak diminati

  19. Curve Finance表示:

    I have seen many useful things on your site about personal computers. However, I have got the opinion that laptop computers are still less than powerful more than enough to be a wise decision if you usually do projects that require many power, like video modifying. But for world wide web surfing, microsoft word processing, and most other common computer functions they are perfectly, provided you can’t mind the small screen size. Thank you for sharing your opinions.

  20. ThomasThype表示:

    Slot modern memiliki grafik yang mengesankan: garuda888 – garuda888

  21. Simply want to say your article is as astonishing. The clearness for your publish is simply excellent and i can think you’re an expert on this subject. Well along with your permission allow me to take hold of your feed to stay updated with coming near near post. Thank you a million and please keep up the gratifying work.

  22. ThomasThype表示:

    Kasino di Indonesia menyediakan hiburan yang beragam: garuda888 – garuda888 slot

  23. ThomasThype表示:

    Banyak pemain menikmati jackpot harian di slot: preman69 slot – preman69.tech

  24. Williecrady表示:

    Mesin slot menawarkan berbagai tema menarik http://bonaslot.site/# Keseruan bermain slot selalu menggoda para pemain

  25. DavidCooth表示:

    http://slot88.company/# Kasino di Jakarta memiliki berbagai pilihan permainan

  26. Aaronbus表示:

    slot demo slot demo Pemain harus menetapkan batas saat bermain

  27. DavidCooth表示:

    https://slot88.company/# Slot dengan bonus putaran gratis sangat populer

  28. Williecrady表示:

    Kasino menyediakan layanan pelanggan yang baik https://preman69.tech/# Slot dengan fitur interaktif semakin banyak tersedia

  29. Williecrady表示:

    Kasino selalu memperbarui mesin slotnya http://garuda888.top/# Mesin slot digital semakin banyak diminati

  30. ThomasThype表示:

    Mesin slot dapat dimainkan dalam berbagai bahasa: BonaSlot – BonaSlot

發佈留言

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