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

39,094 Responses

  1. More articles like this would make the internet more useful.

  2. Excellent read, I just passed this onto a friend who was doing a little research on that. And he actually bought me lunch since I found it for him smile So let me rephrase that: Thank you for lunch!

  3. One more thing I would like to say is that instead of trying to suit all your online degree tutorials on days of the week that you end work (considering that people are drained when they go back home), try to receive most of your sessions on the weekends and only one or two courses for weekdays, even if it means a little time away from your saturday and sunday. This is beneficial because on the saturdays and sundays, you will be a lot more rested in addition to concentrated upon school work. Many thanks for the different points I have acquired from your weblog.

  4. certainly like your web-site however you need to take a look at the spelling on quite a few of your posts. A number of them are rife with spelling problems and I to find it very bothersome to inform the reality then again I?ll surely come back again.

  5. LorenOmigo表示:

    cialis 30 mg dose: TadalAccess – tadalafil tablets side effects

  6. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт холодильников gorenje цены, можете посмотреть на сайте: срочный ремонт холодильников gorenje
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  7. Arthur Jones表示:

    You’ve undoubtedly researched well.

  8. Frankiegeops表示:

    https://tadalaccess.com/# cialis generic 20 mg 30 pills

  9. LorenOmigo表示:

    cipla tadalafil review: tadalafil (tadalis-ajanta) – cialis cheap

  10. ScottTrefs表示:

    us cialis online pharmacy: Tadal Access – cialis pricing

  11. Hello just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Safari. I’m not sure if this is a formatting issue or something to do with browser compatibility but I thought I’d post to let you know. The style and design look great though! Hope you get the issue solved soon. Thanks

  12. Josephmew表示:

    evolution peptides tadalafil whats the max safe dose of tadalafil xtenda for a healthy man cialis substitute

  13. The very root of your writing whilst appearing reasonable in the beginning, did not really settle well with me personally after some time. Someplace within the paragraphs you actually were able to make me a believer but just for a very short while. I nevertheless have got a problem with your jumps in logic and one might do well to fill in those breaks. When you actually can accomplish that, I would certainly end up being impressed.

  14. Josephmew表示:

    cialis and cocaine cialis dosage for bph canadian online pharmacy no prescription cialis dapoxetine

  15. Frankiegeops表示:

    https://tadalaccess.com/# buy cialis canadian

  16. Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! By the way, how could we communicate?

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

  18. This is the kind of post I find helpful.

  19. LorenOmigo表示:

    how long does it take for cialis to start working: difference between cialis and tadalafil – tadalafil 20mg canada

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

  21. great points altogether, you just gained a new reader. What would you suggest in regards to your post that you made some days ago? Any positive?

  22. Daniel Patel表示:

    I genuinely liked the style this was explained.

  23. Robert Taylor表示:

    The thoroughness in this article is noteworthy.

  24. Michaelbug表示:

    click here for more info nivea japan iOS

發佈回覆給「Michaelbug」的留言 取消回覆

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