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

10,979 Responses

  1. EdwardGROOM表示:

    Pharmacie en ligne livraison Europe: acheter kamagra site fiable – pharmacie en ligne france fiable

  2. I can’t express how much I value the effort the author has put into writing this exceptional piece of content. The clarity of the writing, the depth of analysis, and the plethora of information presented are simply impressive. Her zeal for the subject is obvious, and it has definitely resonated with me. Thank you, author, for sharing your knowledge and enlightening our lives with this exceptional article!

  3. EdwardGROOM表示:

    Pharmacie sans ordonnance: kamagra pas cher – pharmacie en ligne fiable

  4. Ignacioreura表示:

    pharmacie en ligne pas cher: Levitra acheter – pharmacie en ligne france livraison internationale

  5. KeithKef表示:

    pharmacie en ligne fiable cialis generique pharmacie en ligne sans ordonnance

  6. O cassino mais confiavel para voce Fortune Tiger

  7. obviously like your web site but you have to check the spelling on quite a few of your posts. Many of them are rife with spelling issues and I find it very bothersome to tell the truth nevertheless I will surely come back again.

  8. Eu recomendo o melhor cassino Fortune Tiger

  9. Thanks for your information on this blog. Just one thing I would like to say is the fact purchasing consumer electronics items in the Internet is not something new. In reality, in the past few years alone, the market for online electronic products has grown significantly. Today, you will find practically just about any electronic unit and gizmo on the Internet, which include cameras along with camcorders to computer elements and gaming consoles.

  10. O melhor cassino do mundo Fortune Tiger

  11. Allenacurf表示:

    Viagra vente libre pays: viagra en ligne – Viagra pas cher paris

  12. RobertBlica表示:

    https://cenligne.com/# pharmacie en ligne france livraison belgique

  13. One thing I’d like to discuss is that weightloss routine fast can be achieved by the perfect diet and exercise. An individual’s size not merely affects appearance, but also the complete quality of life. Self-esteem, major depression, health risks, in addition to physical skills are affected in putting on weight. It is possible to do everything right and at the same time having a gain. If this happens, a problem may be the perpetrator. While an excessive amount of food rather than enough workout are usually the culprit, common health concerns and key prescriptions can greatly add to size. Thanks alot : ) for your post in this article.

  14. Thank you for sharing superb informations. Your site is very cool. I am impressed by the details that you?ve on this blog. It reveals how nicely you perceive this subject. Bookmarked this website page, will come back for more articles. You, my friend, ROCK! I found simply the info I already searched everywhere and simply couldn’t come across. What an ideal web site.

  15. RobertBlica表示:

    https://levitraenligne.com/# pharmacie en ligne avec ordonnance

  16. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Many thanks!

  17. zamki_woPn表示:

    открытие замков дверей http://www.famagusta-nedvizhimost2.ru/ .

  18. Audio began playing anytime I opened up this webpage, so annoying!

  19. I?ll right away grab your rss feed as I can not find your email subscription link or newsletter service. Do you’ve any? Kindly let me know in order that I could subscribe. Thanks.

  20. RalphSnize表示:

    Farmacia online miglior prezzo: farmacia online senza ricetta – farmacie online autorizzate elenco

  21. VernonRib表示:

    https://eufarmaciaonline.com/# farmacia en casa online descuento

  22. RalphSnize表示:

    Farmacia online piГ№ conveniente: acquistare farmaci senza ricetta – farmacia online piГ№ conveniente

  23. AntoniaSut表示:

    online apotheke versandkostenfrei: internet apotheke – online apotheke versandkostenfrei

  24. WilliamTeath表示:

    online apotheke preisvergleich: medikament ohne rezept notfall – internet apotheke

  25. Donaldcoums表示:

    farmacias online seguras: farmacia online madrid – farmacia online barata y fiable

  26. WilliamTeath表示:

    online apotheke gГјnstig: gГјnstigste online apotheke – gГјnstige online apotheke

  27. Roberthep表示:

    farmacie online sicure top farmacia online farmacie online autorizzate elenco

  28. AntoniaSut表示:

    farmacia online barata: farmacias online seguras en espa̱a Рfarmacia online 24 horas

  29. pit viper gun表示:

    Wow, marvelous blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, as well as the content!

發佈留言

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