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

  1. Dereketerm表示:

    cheap priligy: Priligy tablets – cheap priligy

  2. Not a guarantee, but a chance.

  3. A glass-block window in a shower or beside a bathtub floods the bathing area with sunshine however protects our privateness so we acquire the best of each worlds.

  4. Dereketerm表示:

    buy amoxicillin 500mg capsules uk: cheap amoxil – amoxicillin 500mg without prescription

  5. There’s that thrill as you nod to your newly-discovered team mate whereas the remainder of the desk have their eyes shut, that desperation as the web tightens and the finger of suspicion begins to level your way.

  6. The word “T-shirt” is formally added to the Merriam-Webster dictionary.

  7. Audrey Anne Dawson, Consultant Haematologist, Grampian Well being Board.

  8. There’s definitely proof of Buddhist settlement at Nagarjunakonda predating the establishment there of the Iksvaku capital, and it is probably here that we should search for the home of the Aparasaila sect for whose benefit, in the reign of the Iksvaku monarch Mathariputra Virapurusadatta, there was erected the mahacaitya, a dhatugarbha, which must have contributed to the superstar of the positioning in the Buddhist world, while the Purvasaila sect had long been established in places further east, primarily at Amaravati.

  9. 肆 とは表示:

    The concept is similar and you should not accept one precept for them, however another for your self.

  10. 5 points for every phrase that 5 individuals had in common.

  11. 34.) Certainly one of the most popular message boards on the web is GameFAQs’ Life, the Universe, and Every little thing.

  12. Pogba has gained the World Cup, four Serie A titles and the Europa League with United.

  13. Each person in an workplace requires an additional desk.

  14. As soon as in place, the fish will mechanically translate any language within the galaxy to the native tongue of the host.

  15. 33. Retrieved January 13, 2022.; “Rod Beaton”.

  16. 23251336 Corporal Alan James Oldham, Royal Corps of Alerts.

  17. John Gibb Bothwell, Scottish Secretary, Transport Salaried Staffs’ Affiliation.

  18. Bradleygoath表示:

    buy priligy max pharm [url=http://priligymaxpharm.com/#]cheap priligy[/url] Priligy tablets

  19. At the identical time, have proper analysis about the hair pros in the world and book a specialised consultation.

  20. Extraordinarily clearly, you do not actually have to observe any such rule obtainable as one household your house.

  21. If they’re caught at the end they lose, nevertheless, in order that they should pretend to be aiding the team.

  22. なる 意味表示:

    A number of influential right-wing pundits have backed the ‘No Food, No Farmers’ campaign – among them a number of presenters from British broadcaster GB Information, which often assaults climate science and insurance policies.

  23. Differentiate it from howlite, in which the floor has a veining pattern that is mild and grey.

  24. If you’re studying this blog submit then you are more than likely not being paid on your time or place of work.

  25. Connor Stalions reacts to the suggestion that he secretly attended video games after his suspension from school soccer in 2023 👀 Untold: Signal Stealer is now enjoying.

  26. crypto news表示:

    Thanks for helping me to obtain new ideas about desktops. I also have belief that certain of the best ways to help keep your mobile computer in perfect condition is a hard plastic case, or maybe shell, that fits over the top of one’s computer. These kind of protective gear usually are model specific since they are made to fit perfectly within the natural casing. You can buy all of them directly from the owner, or from third party places if they are for your notebook, however not all laptop can have a shell on the market. Again, thanks for your tips.

  27. 6:10-18 and the holy phrase of God.

  28. I learned more new stuff on this losing weight issue. Just one issue is that good nutrition is tremendously vital if dieting. A big reduction in fast foods, sugary foodstuff, fried foods, sugary foods, beef, and white colored flour products might be necessary. Having wastes parasitic organisms, and toxins may prevent goals for losing fat. While specified drugs temporarily solve the issue, the awful side effects are not worth it, and they never provide more than a short lived solution. This is a known idea that 95 of fad diets fail. Thank you for sharing your thinking on this blog.

  29. There are various instances during individuals’s lives that they require the usage of extra storage area.

發佈留言

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