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

  1. The cost of this building venture was 24.5 million euros.

  2. Wilson, Jade (26 July 2021).

  3. Despite the appreciable value reduction, the VAG made a profit of 250,000 Deutsche Marks in 1985 alone.

  4. 屈読み方表示:

    Crooks scored 2,734 factors in highschool, third-most all-time among Iowa girls, and set an all-class, state-tournament record with 49 factors in the 2023 Class 1A championship recreation.

  5. Reginald Percival Smith, Station Officer, Wiltshire Hearth Brigade.

  6. In 2008, Global Fund for Youngsters was chosen as a winner of the John D. and Catherine T. MacArthur Basis’s Digital Media and Studying Competition.

  7. jfr 株価表示:

    The inspiration for “You Belong With Me” did not come from a situation that Swift straight skilled however through her buddy’s.

  8. I will tell you, I used to be listening to the Mayor speak, listening to Marcy talk, and I assumed there’s more energy in Toledo than every other place in America.

  9. Attaining this would require more high finish accommodation and amenities to be built.

  10. It has been suggested that this is the building at the moment known as the Priest House, but no structural proof exists to support this declare.

  11. Apply Plumbing Exams YouTube channel has exams and much more.

  12. promotions表示:

    There are certainly a whole lot of details like that to take into consideration. That may be a nice level to deliver up. I offer the ideas above as general inspiration however clearly there are questions like the one you bring up where the most important thing can be working in honest good faith. I don?t know if greatest practices have emerged round issues like that, but I am certain that your job is clearly identified as a fair game. Both girls and boys feel the impression of just a moment?s pleasure, for the remainder of their lives.

  13. The demons are commanded to confuse, and sow terror and panic within the hearts of those practicing new age, occultism, witchcraft and Satanism.

  14. If not, guess what the artist is making an attempt to attract.

  15. Anthony’s lighting advice on inverts turned me onto HQI’s for my shallow tank and deeper water corals.

  16. Daring Books. Arthur Gerald Contact, Authorities Communications Headquarters.

  17. Most importantly although, you want to treat these things as your own.

  18. ロキ 2話表示:

    Joiner, Royal Aircraft Establishment, Ministry of Provide, Farnborough.

  19. McNally, Tadgh (29 December 2021).

  20. The key distinction is that Gaga Ball uses a playing pit and the ball is rolled alongside the bottom.

  21. Step 1: Draw a particular picture on every paper plate to your friends.

  22. How will fallout affect unprotected livestock, that’s, animals in fields, postures, and different open areas?

  23. Miskatonic University students are being found useless, and it’s as much as you to uncover the truth.

  24. If and when a brand new funding set can be authorized, $50 million would be obtainable for grade crossing elimination initiatives.

  25. But when the compensation at your present employment isn’t passable, furthering your degree might open doors to higher positions.

  26. When the Helmsley Constructing was completed, the copper roof was gilded, but by the late 1950s had been painted inexperienced.

  27. In my view, if in case you have $40,000 to spend money on actual estate properties, you have got a number of good selections.

  28. When the Helmsley Constructing was completed, the copper roof was gilded, but by the late 1950s had been painted inexperienced.

  29. shopping表示:

    Yesterday, while I was at work, my sister stole my iphone and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views. I know this is totally off topic but I had to share it with someone!

發佈留言

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