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

15,446 Responses

  1. Earlier than the pandemic, Portland was rife with happy hours providing dozens of inventive drink and food pairings that might keep summer diners busy for years.

  2. This loafer-type flat has a durable rubber sole that’s designed to hug your arches and provide comfortable assist because of Vionic’s proprietary Vio-Motion technology.

  3. This journey hiking footwear will give you a snug hiking expertise and likewise keep your feet protected.

  4. But if you’re monster hunting in the overworld and another player outside of your party has tagged the goal, you won’t be eligible.

  5. Nonetheless, it is at all times a bonus after i discover stylish travel strolling shoes.

  6. The Bible may be very specific as to what turned of Joseph’s physique.

  7. Though pyjamas are designed to be snug, in case you sometimes sleep in an outdated T-shirt and worn-out sweats, you could have found that your sleepwear does not always work when you’re not at dwelling.

  8. With Memory Foam insoles, arch support and rubber soles, Skechers are good strolling shoes for journey – as you possibly can walk for miles!

  9. Профессиональный сервисный центр по ремонту парогенераторов в Москве.
    Мы предлагаем: ремонт парогенераторов в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  10. Chip lay back towards the cushions and smoked lazily, his eyes half closed, dreaming rather than thinking.

  11. On high of the physical symptoms of anxiety, I seen that as the job grew extra stressful, my temper tumbled downwards until I used to be in a state of depression for months at a time.

  12. 2. You won’t get wealthy from the positioning, but anything helps!

  13. All over the place, down each road, have been an infinite array of retro second hand shops.

  14. “If you don’t have supportive footwear, you’ll be able to develop heel and hip ache so it’s key to discover a pair that works on your foot and test it out at residence before you journey,” she said.

  15. JamesMix表示:

    comprar viagra sin gastos de envГ­o: comprar sildenafilo cinfa 100 mg espaГ±a – viagra 100 mg precio en farmacias

  16. I virtually completely order sneakers from Zappos if I’m buying them online-they provide you with free supply (which is often one or two-day transport) and free returns.

  17. If you’re strolling on cobblestones, essentially the most snug strolling shoes for girls might be ones with a thicker sole, as opposed to what you’d need in the event you have been strolling by means of a Hong Kong mall.

  18. JamesMix表示:

    farmacia online madrid: precio cialis en farmacia con receta – п»їfarmacia online espaГ±a

  19. For most travelers a valid passport is all that’s required to enter Argentina.

  20. Vitality -efficient lighting is using artificial mild to obtain the optimum stage of mild for the lowest energy funding.

  21. DennisRep表示:

    https://farmaciaeu.com/# farmacia online envГ­o gratis

  22. Let’s try the different kinds of wolf minimize hair you possibly can wear on lengthy hair!

  23. slot online表示:

    There are some interesting cut-off dates in this article but I don?t know if I see all of them heart to heart. There’s some validity but I’ll take hold opinion till I look into it further. Good article , thanks and we want extra! Added to FeedBurner as effectively

  24. JamesMix表示:

    farmacia online barata y fiable: farmacia online barata – farmacia online envГ­o gratis

  25. DennisRep表示:

    https://farmaciaeu.com/# farmacia online espaГ±a envГ­o internacional

  26. This curly wolf reduce is a should-attempt for each curly woman who considers a brief haircut.

  27. Consolation is an important factor on any date, and UGG Traditional Minis ship unparalleled consolation through their sheepskin lining, cushioned insole, versatile sole, and roomy match.

  28. DennisRep表示:

    http://farmaciaeu.com/# farmacia online madrid

  29. The stairs and banister that result in a second-flooring museum came from Douglas’ former south grade faculty.

  30. Travelers must surrender their passports and stay in self-isolation for seven days, with an extra take a look at being performed on the seventh day in isolation.

發佈留言

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