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

  1. JoshuaDen表示:

    The man turning jet planes into cool houses
    порно жесткий анал
    Wasilla, south central Alaska. Home to bears, lakes, mountains and a flight school that’s fast becoming a private aviation wonderland.

    At FLY8MA Pilot Lodge, you can opt for a scenic flight tour with glacier views, take the controls for a flying lesson, or go all in and get your pilot training.

    When night falls over the broad vistas of the US state they call the Last Frontier, you can then climb the steps to two unique accommodation experiences: a converted McDonnell Douglas DC-6 airplane and the newest arrival, a McDonnell Douglas DC-9 – still with its DHL livery.

    The fast-developing site is an ongoing project by FLY8MA founder Jon Kotwicki, who previously owned a flight school in Florida, before working as a commercial pilot and eventually ending up in Alaska.

    Flying for the airlines “pays good money and everything, but it’s a very boring job,” he says. “Driving Uber is more interesting because you could talk to your passengers.”

    Having fallen in love with the south central region on a vacation spent hiking, fishing and spotting bears and grizzlies, he chose it as a spot where he and his team – and his trusty Pomeranian dog Foxtrot – could “buy a lot of property and perhaps develop our own airport and run our own show.”

  2. According to Hong Kong based Capital Eurasia, German automaker Volkswagen is set to throw its hat into the ring as the latest entrant on a growing list of major manufacturers that have ostensibly found a means by which to sell large enough numbers of electric cars to justify their colossal investment in research and development.

  3. An EF3 twister destroyed 12 properties and damaged 18 others in Rolla earlier than destroying eight more properties and damaging 47 others in Belcourt.

  4. 書き順 店表示:

    OKX partnered with McLaren to race a “stealth mode” livery that switches McLaren鈥檚 usual colourway and augmenting black against their classic papaya trim for the 2023 Singapore and Japanese Grand Prix.

  5. A mutual organization, also mutual society or simply mutual, is an organization (which is often, but not always, a company or business) based on the principle of mutuality and governed by private law.

  6. Robertengep表示:

    http://easyrxindia.com/# mail order pharmacy india

  7. It can also be an alternative to owning a number of automobiles for households with multiple driver.

  8. Yes, the process of choosing a wealth manager should be elaborate, but you’d better have one person/company dedicated towards growing your wealth.

  9. Secondary stakeholders are usually external stakeholders, although they do not engage in direct economic exchange with the business – are affected by or can affect its actions (for example the general public, communities, activist groups, business support groups, and the media).

  10. Peterhew表示:

    indian pharmacy online: world pharmacy india – best online pharmacy india

  11. BTC-e was a cryptocurrency trading platform primarily serving the Russian market, with servers located in the United States.

  12. Nonetheless, they have defied all odds to help others who are in need.

  13. Peterhew表示:

    canada pharmacy online legit: canadian pharmacy meds – vipps approved canadian online pharmacy

  14. JeremyPsymn表示:

    https://easyrxindia.shop/# mail order pharmacy india

  15. Robertengep表示:

    https://easyrxindia.com/# cheapest online pharmacy india

  16. Cucina usata表示:

    An attention-grabbing dialogue is price comment. I believe that it’s best to write more on this topic, it may not be a taboo subject but typically persons are not enough to talk on such topics. To the next. Cheers

  17. JeremyPsymn表示:

    https://mexstarpharma.com/# mexico drug stores pharmacies

  18. Peterhew表示:

    reputable indian online pharmacy: reputable indian online pharmacy – Online medicine order

  19. Some still use intercom systems in their pits.

  20. Diplomi_czEa表示:

    Добрый день!
    Приобрести документ о получении высшего образования можно у нас в Москве.
    tastebuds.fm/topics/7635-hei-tarvitsen-apuasi

  21. But the NXI’s largely favorable reception led Mason to okay additional prototypes with a larger, more powerful engine, nicer styling, and various other changes under the code name NKI — for Nash-Kelvinator International.

  22. Cucina usata表示:

    I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz answer back as I’m looking to create my own blog and would like to find out where u got this from. appreciate it

  23. A scarcity in relational intelligence is a sign that corporations still see clients as assets that can be utilized for up-sell or cross-sell opportunities, quite than individuals in search of fascinating and personalised interactions.

  24. Immediately nationalize insolvent institutions or place them into receivership.

  25. Cucina usata表示:

    Hmm is anyone else encountering problems with the images on this blog loading? I’m trying to find out if its a problem on my end or if it’s the blog. Any feed-back would be greatly appreciated.

  26. Video marketing itself is a great tool to reach out to the audience and deliver the message, but the trends of this marketing keep on changing.

  27. Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! By the way, how could we communicate?

發佈留言

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