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

  1. ragnaork表示:

    I do agree with all of the ideas you have presented in your post. They are really convincing and will definitely work. Still, the posts are very short for beginners. Could you please extend them a bit from next time? Thanks for the post.

  2. Demerits: Its capabilities are limited, again it is offered in brown shade and used for particular purposes; transportation, transport, stocking and storage function.

  3. 得て 英語表示:

    With this ultimate guide to Argentina travel insurance coverage, you’ll be able to tango via the streets with peace of thoughts.

  4. Glass is positioned on the reception desk, which is an option.

  5. These exterior teams are referred to as Individual Observe Associations (IPA).

  6. Packing styles can be a private choice and there’s many ideas on the market on methods to do it.

  7. Assuming that he was travelling alone, he was once once more typical, because at that point, younger, single males have been by far the most likely to make such a journey.

  8. UGGs are most effectively-recognized for its line of women’s boots, but the corporate also supplies slippers and footwear to provide you with a high quality product for every occasion.

  9. Only some key bits of infrastructure and all underneath the control of 1 entity that can be sure its staff observe acknowledged guidelines “or else” is inherently simpler than a complex network with a huge variety of individuals.

  10. Free men will not be equal.

  11. Leonardville (Kan.) — History.

  12. • Shops. Working carefully with manufacturing partner ùɡȫőˀ Ǡʀ ʸőɱ ǂƜȂʀ ʀǗőʀ ő žȫȔŵǠȚőʀǠȫȚ ȫǂ ƉȫʗŵȂƜ őȚƉ ɱǠȚDžȂƜ ɱǼǠȚ ɱʀƜƜȂ ɖőɡʀǠʀǠȫȚɱ ʸȫʗȂƉ ŵƜ the proper answer and offers many őƉʴőȚʀőDžƜɱ ȫʴƜɡ ő ʀɡőƉǠʀǠȫȚőȂ ɖȂőɱʀƜɡŵȫőɡƉ ȫɡ ʀǠȔŵƜɡ ɖɡȫƉʗžʀ ࡑ Steel Partitions are formed from a panel ɱˁɱʀƜȔ ʀȫ ƉǠʴǠƉƜ őȚƉ ɱʗŵƉǠʴǠƉƜ ʀǗƜ ʸȫɡǼɖȂőžƜ and are commonly utilized in a warehouse and manufacturing unit surroundings.

  13. Hawaii Bathrooms – Hello Bathroom Listings.

  14. The time interval is important as a result of the development contract usually includes cash penalties towards the builder within the occasion the mission runs late.

  15. I haven?t checked in here for some time since I thought it was getting boring, but the last several posts are good quality so I guess I will add you back to my daily bloglist. You deserve it my friend 🙂

  16. Job spells shouldn’t be used to govern or hurt others for personal acquire.

  17. It allows anyone to create unique and excessive-high quality customized goods whether ordering only one merchandise or 1,000 items while at the identical time providing a handbook order function for these with out e-commerce expertise.With it, you may sync existing product listings from your on-line retailer to CustomCat seamlessly, create product templates and mass publish product listings with bulk tools, manage product listings, view stock standing and edit success settings, and manage all aspects of orders and achievement.

  18. Always remembering that it’s a system and that brings me to another point – one of the largest mistakes we’re making is economic ideology insisting on pretending there’s multiple techniques when in reality there’s just one.

  19. Hey! Do you use Twitter? I’d like to follow you if that would be ok. I’m undoubtedly enjoying your blog and look forward to new posts.

  20. I just could not depart your site prior to suggesting that I really enjoyed the standard info a person provide for your visitors? Is going to be back often to check up on new posts

  21. 見い出す表示:

    So if you’re partying up with pals and the spell targets one of them, you continue to get an opportunity at studying it.

  22. Not solely did having dangerous sneakers damage my trip but it also took me a month to recover after I acquired dwelling.

  23. This oil can be used to anoint candles or for sigil work.

  24. So one should use engineering to discard the 99.9 of people who don’t have any clue what’s going on.

  25. Edisonanazy表示:

    comprare farmaci online con ricetta: Farmacie on line spedizione gratuita – Farmacie online sicure

  26. What Did The Males Wore For a hundred Plus Years?

  27. 藤井六段表示:

    Moreover all these germs, I also brought you this photograph of stated seaside right after sunset: Sunset on the Egmond aan Zee seashore.

  28. For people who need to look for work in Germany.

  29. Irrevocable trusts usually can’t be changed as soon as they’re arrange.

  30. These individuals have a wealth of knowledge and might supply insights, spell suggestions, and help in your magical observe.

發佈留言

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