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

  1. RobertWAisa表示:

    reputable indian online pharmacy Indian pharmacy international shipping Online medicine order

  2. RobertWAisa表示:

    mexico drug stores pharmacies medication from mexico purple pharmacy mexico price list

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

  4. Thanks for discussing your ideas. I might also like to convey that video games have been ever before evolving. Technology advances and improvements have aided create sensible and enjoyable games. These kinds of entertainment video games were not really sensible when the actual concept was first being attempted. Just like other areas of technology, video games too have had to evolve by many many years. This is testimony on the fast growth and development of video games.

  5. Timothystoft表示:

    best online pharmacies in mexico: medication from mexico – purple pharmacy mexico price list

  6. Hi, i feel that i saw you visited my web site thus i came to ?go back the desire?.I am trying to in finding things to enhance my web site!I suppose its ok to use a few of your ideas!!

  7. Тактичный гардероб для стильных людей, тактичные наряды.
    Где найти тактичный стиль в одежде, которые должен знать каждый.
    Как создать стильный образ с тактичной одеждой, которые не выйдут из моды.
    Какие аксессуары подойдут к тактичной одежде, для создания армейского образа.
    Как не ошибиться с выбором тактичной одежды, чтобы быть в центре внимания.
    військова тактична одежа військова тактична одежа .

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

  9. RobertWAisa表示:

    buying from online mexican pharmacy mexican pharma buying prescription drugs in mexico

  10. RogerTut表示:

    purple pharmacy mexico price list: mexican pharma – mexican online pharmacies prescription drugs

  11. RogerTut表示:

    pharmacies in mexico that ship to usa: medication from mexico – best online pharmacies in mexico

  12. Jamesruigo表示:

    http://canadapharma.shop/# the canadian pharmacy

  13. RogerTut表示:

    mexican pharmaceuticals online: medication from mexico – mexican drugstore online

  14. Jamesruigo表示:

    https://mexicanpharma.icu/# medicine in mexico pharmacies

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

  16. Timothystoft表示:

    п»їbest mexican online pharmacies: mexico drug stores pharmacies – mexican rx online

  17. Jamesruigo表示:

    http://indiadrugs.pro/# buy medicines online in india

  18. Hey, you used to write magnificent, but the last few posts have been kinda boring? I miss your great writings. Past few posts are just a little bit out of track! come on!

  19. Heya i am for the first time here. I found this board and I to find It truly helpful & it helped me out much. I’m hoping to present one thing back and help others such as you helped me.

  20. Thanks for your article. It’s very unfortunate that over the last one decade, the travel industry has already been able to to fight terrorism, SARS, tsunamis, influenza, swine flu, and also the first ever entire global tough economy. Through everything the industry has proven to be strong, resilient plus dynamic, finding new strategies to deal with hardship. There are often fresh difficulties and the opportunity to which the marketplace must once more adapt and act in response.

  21. I really like what you guys tend to be up too. Such clever work and reporting! Keep up the superb works guys I’ve included you guys to my personal blogroll.

  22. You can definitely see your skills within the work you write. The world hopes for even more passionate writers like you who aren’t afraid to say how they believe. At all times follow your heart.

  23. I love what you guys are up too. Such clever work and exposure! Keep up the amazing works guys I’ve incorporated you guys to my blogroll.

  24. I have noticed that good real estate agents just about everywhere are Marketing and advertising. They are seeing that it’s not just placing a sign post in the front yard. It’s really concerning building connections with these suppliers who sooner or later will become customers. So, when you give your time and energy to aiding these dealers go it alone – the “Law associated with Reciprocity” kicks in. Good blog post.

  25. Sergiohex表示:

    http://rybelsus.tech/# rybelsus generic

  26. JosephFam表示:

    generic lasix: furosemide online – lasix 100 mg

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

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

  29. Amazing! This blog looks exactly like my old one! It’s on a totally different topic but it has pretty much the same page layout and design. Wonderful choice of colors!

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

發佈留言

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