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,427 Responses

  1. ArthurKib表示:

    https://pharmbig24.online/# best online pharmacies no prescription

  2. Hi, i believe that i noticed you visited my website thus i came to ?return the want?.I’m trying to find issues to improve my site!I suppose its good enough to use a few of your ideas!!

  3. RobertMef表示:

    reputable mexican pharmacies online: purple pharmacy mexico price list – п»їbest mexican online pharmacies

  4. I would like to thank you for the efforts you have put in writing this site. I’m hoping the same high-grade site post from you in the upcoming as well. In fact your creative writing skills has inspired me to get my own website now. Really the blogging is spreading its wings fast. Your write up is a good example of it.

  5. C ontent w​as c​re at ed by GSA​ Content  Gen er ator DEMO.

  6. Josephfub表示:

    mexico drug stores pharmacies purple pharmacy mexico price list mexican rx online

  7. Josephfub表示:

    best online pharmacies in mexico mexican rx online purple pharmacy mexico price list

  8. Within the accounting major, college students who take the Advanced Accounting course can take an examination to acquire Certified Public Accountant skills.

  9. London: Oxford Enterprise Group.

  10. It was also a more-potent huge Ford with adoption of the 4.6-liter overhead-cam V-eight first seen in the ’91 City Automobile.

  11. RobertMef表示:

    indian pharmacy paypal: Online medicine order – best india pharmacy

  12. Do you envision a basement or storage the place you can have a workshop or area for a house office?

  13. Rock Island, IL. March 30, 1891.

  14. On April 27, Disney announced that a lot of the Fox Networks Group Asia Pacific linear channels could be shut down in two phases in October 2021 for Hong Kong and Southeast Asian nations and January 2022 for Taiwan, respectively.

  15. Revision includes, as an illustration, incorporating references to other issued security standards (equivalent to ISO/IEC 27000, ISO/IEC 27004 and ISO/IEC 27005) and varied good security practices which have emerged in the sector since they had been last published.

  16. RobertMef表示:

    erectile dysfunction causes: accutane mexican pharmacy – russian pharmacy online

  17. Office 2010 supplies learn assist for ECMA-376, read/write support for ISO/IEC 29500 Transitional, and browse assist for ISO/IEC 29500 Strict.

  18. Among the business core modules are lessons in Analysis & Statistics for Managers, Accounting for the Contemporary Manager and Administration Information Techniques, so the analytic instruments and IT necessities for a Masters in Finance are coated in the first half of the program.

  19. American teams with out Whitaker have been ready to say the Olympiad workforce gold medals for 1931, 1933, 1935 and 1937, together with many particular person medals.

  20. They know at the end of the day, the job is to get a deal executed; nevertheless, it will never be on the expense of a sub-par settlement.

  21. Th is was c᠎reat᠎ed by GSA Content Gener at​or Demoversion.

  22. An extra $675 million in securities was transported to the new structure, protected by a hundred armored cars with machine guns.

  23. A complete of eight tornadoes had been confirmed.

  24. 21, Sequence of 2008.

  25. ArthurKib表示:

    https://pharmbig24.online/# prescriptions online pharmacy

  26. Linda Magri, an actual estate broker who rents summer homes and camps on the island.

  27. In accordance with this argument, an organization must recognize that individuals have many various kinds of relationships with completely different manufacturers.

  28. Indian Oil Corporation (Could 16, 2023).

  29. MauriceGueda表示:

    top online pharmacy india: Online medicine home delivery – reputable indian pharmacies

發佈留言

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