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

17,189 Responses

  1. Horvath was named to the 23-man U.S.

  2. One lady is hatless and is seen in a fairly pink and white layered check dress, the other in a power blue layered costume with a white (now discoloured) shawl.

  3. Hanna Ljungberg appeared at three European Championship tournaments: Norway/Sweden 1997, Germany 2001, and England 2005.

  4. Within the 1970s, Rankin-Bass created animated variations of The Jackson Five Present and The Osmonds.

  5. Gibbons, Fiachra (23 March 2000).”Gallery ‘cheated Bacon out of tens of hundreds of thousands'”.

  6. Oh, and there ought to be mounting holes pre-drilled in the sandpaper punch like there are within the DeWalt and Black & Decker versions we now have – not because it’s extra convenient when mounted, however because in any other case we’d lose the thing.

  7. He uses Ji Gang’s wife to fabricate a lie about Ji’s loss of life to make Ming Tian’s Father look unhealthy but is came upon after the truth is exposed by Fang Zhou and Music Xiaomi and has a coronary heart to coronary heart with Fang Yu about her life and his inability to let her be free.

  8. The school also struggled to keep up coaches as 80 of the teaching workers give up during the season and the group was left with simply two coaches and one player’s mother.

  9. The man was Reginald de Pympe, and his son, John, added more stained glass later in the same century.

  10. Historically, it was thought that eating a small pie on each of the 12 days of Christmas would bring good luck in the brand new Yr.

  11. Birmingham Metropolis are backside, nonetheless looking for their first win of the season.

  12. MST. Actual-time updates through e-mail, the Web, and telecasts are transferred into streaming audio and video updates and then translated into French, Japanese, Spanish, Portuguese, and English.

  13. Wikimedia Commons has media related to Autograph signatures.

  14. However first, it’s vital to know simply how waves get this energy in the first place.

  15. I believe that avoiding prepared foods could be the first step in order to lose weight. They will often taste excellent, but processed foods contain very little nutritional value, making you take more simply to have enough vigor to get over the day. When you are constantly ingesting these foods, transitioning to whole grains and other complex carbohydrates will make you to have more power while eating less. Thanks alot : ) for your blog post.

  16. タイ 正月表示:

    These forces of French exiles and the French Forces of the Interior (FFI) performed varying roles within the liberation of France and the defeat of Vichy France, Nazi Germany, Kingdom of Italy and the Empire of Japan.

  17. In paperweights, the millefiori or sculptural lampwork components are encapsulated in clear strong crystal creating a totally solid sculptural type.

  18. 4911 配当表示:

    His work was influenced by each the Artwork Nouveau and Artwork Deco movements.

  19. This condition is named submit herpetic neuralgia.

  20. They carved the whole lot, together with issues just like the rubber ties, in the foam.

  21. You should also search for enthusiastic, excessive-power representatives who’ve a naturally optimistic angle and an air of confidence about them.

  22. Nice weblog here! Additionally your web site rather a lot up very fast! What host are you the use of? Can I am getting your associate hyperlink on your host? I desire my website loaded up as fast as yours lol

  23. Along with one or two favourite pieces — the mattress, say, and a chest you’ve got had since childhood — odds and ends accumulate, such as a rocker that will not do within the living room or an outdated portrait.

  24. I don’t intend to have the tank filled inside a year, like most I see.

  25. Co-founder Shavitz died in July 2015 on the age of eighty and was buried in Bangor, Maine.

  26. That is one among the principle causes for some celebrities solely giving their signatures for a payment.

  27. A stay-action drama, titled Yumi’s Cells, was launched on September 17, 2021 in South Korea.

  28. This iconic carnival is stuffed with parades, music and colourful costumes, showcasing the city’s vibrant culture and tenacious spirit in all its glory.

  29. A cross tattoo may also be interpreted to signify unrestricted love and self-sacrifice, just as Jesus felt and demonstrated toward the human species.

發佈留言

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