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

11,270 Responses

  1. Artificial Intelligence isn’t here to replace law enforcement officers; it’s here to make them more effective.

  2. DouglasGed表示:

    mexican drugstore online: Mexico pharmacy online – п»їbest mexican online pharmacies

  3. I would like to thank you for the efforts you’ve put in writing this web site. I am hoping the same high-grade website post from you in the upcoming also. Actually your creative writing skills has encouraged me to get my own blog now. Really the blogging is spreading its wings quickly. Your write up is a great example of it.

  4. DouglasGed表示:

    reputable indian pharmacies: indian pharmacy – india pharmacy mail order

  5. As the kinks are worked out and the balance between family and work is steadied, more clients can be added.

  6. I’ve learned some new things by your website. One other thing I’d really like to say is the fact newer personal computer operating systems are inclined to allow additional memory to be played with, but they likewise demand more storage simply to operate. If a person’s computer is unable to handle a lot more memory and the newest software program requires that memory increase, it is usually the time to shop for a new Laptop. Thanks

  7. DouglasGed表示:

    mexican mail order pharmacies: buying prescription drugs in mexico online – reputable mexican pharmacies online

  8. Please let me know if you’re looking for a article author for your site. You have some really good posts and I feel I would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some articles for your blog in exchange for a link back to mine. Please send me an email if interested. Thanks!

  9. The first is an overall trading plan.

  10. Manrqeq表示:

    Здравствуйте!
    Купить документ университета.
    Мы можем предложить дипломы любой профессии по приятным ценам.
    flokii.com/blogs/view/186035

  11. When you move, you sell your stock in the co-op.

  12. Based on my study, after a in foreclosure home is available at an auction, it is common for the borrower to still have the remaining balance on the personal loan. There are many loan merchants who try to have all rates and liens paid off by the next buyer. Nevertheless, depending on specified programs, polices, and state laws there may be several loans that aren’t easily sorted out through the exchange of loans. Therefore, the duty still remains on the borrower that has got his or her property in foreclosure. Thanks for sharing your opinions on this web site.

  13. The term has been used frequently in the 20th and 21st centuries, but the concept has existed in the West for far longer.

  14. Specific contractual agreements between the covered entity and businesses that it relates with must be covered as well.

  15. Thanks for your write-up on the travel industry. I will also like to include that if your senior considering traveling, it truly is absolutely imperative that you buy traveling insurance for senior citizens. When traveling, seniors are at high risk of having a healthcare emergency. Buying the right insurance cover package in your age group can protect your health and provide you with peace of mind.

  16. That building remained the seat of SBF, then Euronext Paris until the latter moved to La D茅fense in 2015.

  17. And, the credit card market in the U.S.

  18. The other day, while I was at work, my sister stole my iphone and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is entirely off topic but I had to share it with someone!

  19. There are lots of ways,that is, how to invest in the share market, they are either free or low cost.

  20. Wow, marvelous weblog structure! How lengthy have you been blogging for? you make running a blog glance easy. The overall glance of your web site is magnificent, as well as the content!

  21. Trefpan表示:

    Добрый день!
    Стоимость дипломов высшего и среднего образования и как избежать подделок
    michiya-cs.com/userinfo.php?uid=31008
    Окажем помощь!.

  22. Lazrnbq表示:

    Привет!
    Мы изготавливаем дипломы психологов, юристов, экономистов и других профессий по выгодным ценам.
    telegra.ph/distancionnoe-obuchenie-v-rossii-vuzy-08-02

  23. I don?t even know how I ended up here, but I thought this post was good. I do not know who you are but certainly you’re going to a famous blogger if you are not already 😉 Cheers!

  24. If you come across loss, this can be greatly harmful for you as it is going to discourage you from making any further investments.

  25. カ・表示:

    RE/MAX is the real estate network that has the most competitive advantages to offer those in the home buying and selling process.

  26. Hopefully, one of these business ideas can inspire you to pursue something satisfying while providing substantial income.

  27. An interesting discussion is price comment. I think that you must write more on this matter, it won’t be a taboo subject however usually individuals are not enough to speak on such topics. To the next. Cheers

  28. You would like a chief who has been managing a fund for a minimum of five years and has an investment style that meets your goals.

  29. BobbyOxymn表示:

    Boost kasiino – ametlik kodulehekulg Eestis: taielik ulevaade
    boost casino estonia
    on Eesti mangurite seas kiiresti populaarsust kogunud. Kaesolevas artiklis vaatleme, miks Boost casino eesti on saavutanud sellise edu, kasitledes selle peamisi funktsioone ja pakutavaid teenuseid, sealhulgas manguvalikuid, boonuseid ja kasutajasobralikku liidest.

    Boostcasino Mangude Ulevaade
    Boost Casino pakub laia valikut ponevaid mange, mis meeldivad igale mangijale, alates algajatest kuni kogenud hasartmangusopradeni. Selles jaotises saate teada, milliseid erinevaid mange Boost Casino pakub, sealhulgas populaarseid manguautomaate ja lauamange, samuti live-kasiino voimalusi, mis pakuvad mangijatele toelist kasiinokogemust mugavalt oma kodus.

    Slotid ja Lauamangud
    Boost Casino’s on esindatud sadu slotimange erinevatelt arendajatelt, nagu NetEnt, Microgaming ja Play’n GO, mis tagab kvaliteetsed graafikad ja sujuva mangukogemuse. Lisaks klassikalistele slotidele leidub laialdaselt lauamange, sealhulgas:

    1. Blackjack: Mitu varianti, nagu klassikaline, Euroopa ja Vegas Strip.
    2. Rulett: Euroopa, Ameerika ja Prantsuse rulett.
    3. Baccarat: Punto Banco ja kiire tempo baccarat.

    Nende mangude RTP (Return to Player) maarad on tavaliselt vaga konkurentsivoimelised, mis tostab mangijate voiduvoimalusi. Boost Casino uuendab regulaarselt oma mangude valikut, pakkudes uusi ja ponevaid variante.

發佈留言

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