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

38,474 Responses

  1. Fantastic website. A lot of useful information here. I?m sending it to some pals ans also sharing in delicious. And certainly, thanks on your sweat!

  2. Josephmew表示:

    pregnancy category for tadalafil cialis 5 mg prices of cialis

  3. Good post. I study something tougher on completely different blogs everyday. It’ll all the time be stimulating to read content from other writers and observe a little bit one thing from their store. I?d choose to make use of some with the content on my blog whether you don?t mind. Natually I?ll offer you a hyperlink in your web blog. Thanks for sharing.

  4. Thanks for the publish. My spouse and i have continually noticed that most people are eager to lose weight simply because wish to appear slim plus attractive. On the other hand, they do not always realize that there are other benefits to losing weight in addition. Doctors claim that over weight people experience a variety of health conditions that can be directly attributed to their excess weight. The good news is that people who definitely are overweight along with suffering from various diseases can help to eliminate the severity of their particular illnesses through losing weight. You possibly can see a steady but marked improvement with health when even a bit of a amount of weight loss is obtained.

  5. Thanks for revealing your ideas. Another thing is that students have a solution between national student loan as well as a private education loan where it is easier to go for student loan consolidating debts than over the federal student loan.

  6. online poker表示:

    I’ve learned quite a few important things by means of your post. I’d personally also like to mention that there may be situation in which you will make application for a loan and do not need a cosigner such as a Federal government Student Aid Loan. In case you are getting that loan through a common financier then you need to be prepared to have a cosigner ready to help you. The lenders are going to base their own decision over a few aspects but the main one will be your credit worthiness. There are some lenders that will additionally look at your work history and make a decision based on this but in almost all cases it will depend on your ranking.

  7. Admiring the persistence you put into your website and in depth information you present. It’s good to come across a blog every once in a while that isn’t the same out of date rehashed information. Fantastic read! I’ve saved your site and I’m adding your RSS feeds to my Google account.

  8. LorenOmigo表示:

    cialis 20 mg duration: Tadal Access – how to buy tadalafil

  9. Game表示:

    Howdy! Would you mind if I share your blog with my facebook group? There’s a lot of folks that I think would really appreciate your content. Please let me know. Many thanks

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

  11. ScottTrefs表示:

    tadalafil how long to take effect: tadalafil daily use – cialis professional ingredients

  12. Kingfgk表示:

    Онлайн чат с психологом без регистрации. Задать онлайн вопрос психологу. Помощь психолога онлайн чат.

    Раздражительность на членов своей семьи.
    Сколько встреч нужно?
    Психологическое консультирование заключается в том, чтобы помочь клиенту разобраться в своих проблемах и вместе с ним найти пути выхода из сложной ситуации.
    Правильно оценить происходящее в жизни и найти выход из сложившейся жизненной ситуации.

  13. Frankiegeops表示:

    https://tadalaccess.com/# cialis copay card

  14. Peoplehig表示:

    Мне нужен психолог. Психолог онлайн чат. Как выйти из депрессии видео.

    Раздражительность на членов своей семьи.
    Задайте интересующие вас вопросы или запишитесь на сеанс к психологу.
    Консультация в кризисных состояниях.
    Анонимный прием.

  15. qq88表示:

    One important thing is that when you’re searching for a student loan you may find that you will need a cosigner. There are many situations where this is correct because you might find that you do not employ a past credit rating so the loan provider will require that you have someone cosign the financial loan for you. Thanks for your post.

  16. Samefs表示:

    Как начать разговор с психологом. Задать вопрос психиатру онлайн. Психолог онлайн отзывы.

    Онлайн сессия от 73175 руб.
    Запись на прием, оплата, подробная информация о специалистах и отзывы клиентов.
    Эмоциональное состояние: тревога, депрессия, стресс, эмоциональное выгорание.

  17. Fatherzoz表示:

    Телеграм психолог. Чат инкогнито. Форум психологической помощи.

    Мы обязательно поможем преодолеть эмоциональный кризис, избавиться от тревожности и апатии, справиться со стрессом и депрессией, связанными с неуверенностью и многим другим.
    Психолог, Сайт психологов.
    Задайте интересующие вас вопросы или запишитесь на сеанс к психологу.

  18. Frankiegeops表示:

    https://tadalaccess.com/# tadalafil tablets 40 mg

  19. Thank you for the auspicious writeup. It actuallywas once a entertainment account it. Look complex to far introduced agreeable from you!However, how can we keep in touch?

  20. Frankiegeops表示:

    https://tadalaccess.com/# mint pharmaceuticals tadalafil

  21. LorenOmigo表示:

    buy cheapest cialis: Tadal Access – vigra vs cialis

  22. qq88表示:

    I?ve learn several good stuff here. Certainly price bookmarking for revisiting. I wonder how a lot effort you put to create the sort of wonderful informative site.

  23. ScottTrefs表示:

    shelf life of liquid tadalafil: Tadal Access – walgreen cialis price

  24. Josephmew表示:

    cialis dapoxetine europe cialis online cheap buy cialis online in austalia

  25. ScottTrefs表示:

    what is cialis good for: buying cialis online canadian order – does cialis shrink the prostate

  26. qq88表示:

    Hello there, I found your blog via Google while searching for a similar topic, your site came up, it seems to be great. I’ve bookmarked it in my google bookmarks.

  27. Frankiegeops表示:

    https://tadalaccess.com/# buy tadalafil online paypal

  28. ScottTrefs表示:

    price of cialis in pakistan: TadalAccess – cialis generic purchase

  29. qq88表示:

    Youre so cool! I dont suppose Ive learn anything like this before. So good to search out someone with some unique thoughts on this subject. realy thanks for beginning this up. this web site is something that is wanted on the net, someone with a little bit originality. useful job for bringing one thing new to the internet!

發佈留言

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