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

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

  2. Jamesruigo表示:

    http://mexicanpharma.icu/# п»їbest mexican online pharmacies

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

  4. Jamesruigo表示:

    https://mexicanpharma.icu/# п»їbest mexican online pharmacies

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

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

  7. Jamesruigo表示:

    https://indiadrugs.pro/# indian pharmacy online

  8. link表示:

    Amazing blog! Do you have any helpful hints for aspiring writers? I’m hoping to start my own site soon but I’m a little lost on everything. Would you advise starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m totally overwhelmed .. Any recommendations? Appreciate it!

  9. link表示:

    magnificent put up, very informative. I ponder why the opposite specialists of this sector don’t understand this. You should proceed your writing. I’m confident, you have a huge readers’ base already!

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

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

  12. RogerTut表示:

    Online medicine order: Indian pharmacy online – indian pharmacy online

  13. RogerTut表示:

    pharmacy website india: Online medication home delivery – top 10 online pharmacy in india

  14. RogerTut表示:

    pharmacies in mexico that ship to usa: mexican pharma – buying prescription drugs in mexico

  15. source表示:

    Magnificent beat ! I would like to apprentice at the same time as you amend your site, how could i subscribe for a blog website? The account aided me a acceptable deal. I were tiny bit acquainted of this your broadcast offered bright clear concept

  16. RobertWAisa表示:

    indian pharmacies safe online Indian pharmacy Online medicine order

  17. RobertWAisa表示:

    reliable canadian pharmacy Pharmacies in Canada that ship to the US canadian 24 hour pharmacy

  18. lawyer表示:

    It’s the best time to make some plans for the long run and it is time to be happy. I have learn this put up and if I may I desire to counsel you few interesting issues or suggestions. Perhaps you could write next articles regarding this article. I desire to learn even more issues about it!

  19. www表示:

    Sweet blog! I found it while searching on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Cheers

  20. Jamesruigo表示:

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

  21. blog表示:

    Pretty section of content. I just stumbled upon your weblog and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I?ll be subscribing to your feeds and even I achievement you access consistently quickly.

  22. Thank you for every other great article. The place else may anyone get that type of information in such an ideal manner of writing? I have a presentation next week, and I am at the look for such information.

  23. law表示:

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

  24. Aw, this was a really nice post. In concept I want to put in writing like this additionally ? taking time and actual effort to make an excellent article? but what can I say? I procrastinate alot and by no means appear to get something done.

  25. law blog表示:

    I have noticed that car insurance organizations know the motors which are liable to accidents along with other risks. In addition, they know what form of cars are inclined to higher risk and the higher risk they have got the higher the particular premium charge. Understanding the simple basics of car insurance just might help you choose the right style of insurance policy that will take care of your preferences in case you happen to be involved in an accident. Thanks for sharing a ideas for your blog.

  26. RobertWAisa表示:

    pharmacy com canada pharmacy rx world canada my canadian pharmacy review

  27. I’m not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come back down the road. Cheers

  28. lawyer表示:

    Thanks for the recommendations on credit repair on this amazing blog. The thing I would advice people is always to give up this mentality that they can buy now and pay out later. Being a society all of us tend to repeat this for many factors. This includes vacations, furniture, as well as items we’d like. However, you have to separate one’s wants out of the needs. When you’re working to improve your credit score you really have to make some trade-offs. For example you’ll be able to shop online to save cash or you can go to second hand suppliers instead of highly-priced department stores for clothing.

  29. Jamesruigo表示:

    https://canadapharma.shop/# canadian pharmacy meds review

  30. Good post. I study something more challenging on totally different blogs everyday. It’ll at all times be stimulating to read content material from different writers and apply a little something from their store. I?d prefer to make use of some with the content on my weblog whether or not you don?t mind. Natually I?ll offer you a hyperlink on your internet blog. Thanks for sharing.

發佈留言

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