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

24,137 Responses

  1. If the idea of partying in the Caribbean for spring break is getting a tad old, United Way has another option for you.

  2. Patrick’s Day celebrations. 26 March 2011 – A fake bull used as the mascot of the Dunderry Fair was placed on the granite plinth, much to the confusion of locals.

  3. Whether or not I’m heading to a café or touring to a writing retreat, the WPT-a hundred and fifty is at all times ready to hitch me.

  4. The location directs you to a different web page with another hyperlink.

  5. mzplay表示:

    Thanks for the interesting things you have disclosed in your text. One thing I would like to touch upon is that FSBO interactions are built with time. By bringing out yourself to owners the first saturday and sunday their FSBO is usually announced, ahead of masses start out calling on Mon, you develop a good relationship. By giving them resources, educational materials, free accounts, and forms, you become a great ally. If you take a personal affinity for them plus their predicament, you produce a solid connection that, many times, pays off once the owners opt with a realtor they know plus trust — preferably you actually.

  6. DavidTouts表示:

    https://slotsiteleri25.com/# slot casino siteleri

  7. By the point of the Normandy Invasion, the Free French forces numbered 500,000 regulars and greater than 100,000 FFI (French Resistance).

  8. Pink and blue together can create a leaping discordant pattern that is quite nasty to take a look at.

  9. It can instantaneously process your test funds and pile up day by day, weekly and month-to-month reports and export to PDF or Excel with apparent accounting mechanisms.

  10. Since the involvement of the village in electoral politics, the caste has crept in politics as well.

  11. You may find yourself lacking clarity or jumping from one job to another without a clear plan.

  12. If Internet OS providers can address issues like the performance hole and information security issues, we would see a dramatic shift in computer network methods.

  13. mzplay表示:

    One other issue is that if you are in a scenario where you do not have a cosigner then you may really need to try to make use of all of your educational funding options. You will discover many funds and other grants that will supply you with money to help with classes expenses. Many thanks for the post.

  14. вывод из запоя стационарно ростов https://vyvod-iz-zapoya-rostov226.ru .

  15. In order to hedge out that risk there was a provision of future trading being evolved which enabled the share holder to trade in a particular product for a predetermined price after a period of time.

  16. Also I believe that mesothelioma cancer is a scarce form of melanoma that is often found in these previously familiar with asbestos. Cancerous cells form within the mesothelium, which is a protecting lining which covers the vast majority of body’s bodily organs. These cells usually form inside the lining with the lungs, mid-section, or the sac which encircles one’s heart. Thanks for giving your ideas.

  17. But if she is really occupied with lots of responsibilities on her part then you should give her some of your time to sort out things.

  18. adult webcams表示:

    Nice post. I be taught something more difficult on completely different blogs everyday. It can all the time be stimulating to read content material from other writers and apply a bit something from their store. I?d want to use some with the content material on my weblog whether you don?t mind. Natually I?ll give you a link on your internet blog. Thanks for sharing.

  19. One who is in the sales and marketing filed would require high importance for leading generation.

  20. Some of the administrative activities included in fund administration include calculation of net asset value, which involve the calculation of income funds, expense accruals and the pricing of securities based on their current market value, the preparation of semi-annual or annual reports to shareholders, maintenance and filing of the fund’s financial books and records, payment of fund expenses and settlement of daily purchases and sales of securities, ensuring collection of dividends and interests to name a few.

  21. BradleyEdino表示:

    Casino Siteleri casino bahis siteleri Canl? Casino Siteleri

  22. вывод. из. запоя. ростов. vyvod-iz-zapoya-rostov225.ru .

  23. sex webcams表示:

    very nice put up, i actually love this website, carry on it

  24. вывод из запоя в ростове-на-дону вывод из запоя в ростове-на-дону .

  25. free cam sex表示:

    It’s a shame you don’t have a donate button! I’d most certainly donate to this fantastic blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to new updates and will share this site with my Facebook group. Chat soon!

  26. вывод из запоя на дому в ростове вывод из запоя на дому в ростове .

  27. врач на дом капельница от запоя врач на дом капельница от запоя .

  28. вывод из запоя на дому ростов цены вывод из запоя на дому ростов цены .

發佈留言

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