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

  1. 能は表示:

    So it’s no surprise that boomers appreciate the perks and features of watching movies or TV shows on a large LCD or plasma flat-screen with audio being piped through the surround-sound speakers of their home entertainment systems.

  2. Darrelherse表示:

    oyun siteleri slot: slot siteleri bonus veren – slot bahis siteleri

  3. 即日 借入表示:

    Iraq Extractive Industries Transparency Initiative (December 7, 2019).

  4. The T-model connects fundamentals with investment return, allowing an analyst to make projections of financial performance and turn those projections into a required return that can be used in investment selection.

  5. Mom Cabrini Highschool (MCHS) was a Catholic high school positioned at 701 Fort Washington Avenue between Fort Tryon Park and West 190th Road, with a facade on Cabrini Boulevard, within the Hudson Heights neighborhood of Washington Heights in Upper Manhattan, New York Metropolis.

  6. I found minimum account sizes ranging from as low as $25,000 to as much as $25 million.

  7. You must be sure of your need for taking life insurance before you can decide about how much and where to take a policy from.

  8. By understanding and recognizing the signs and symptoms of bipolar disorder, individuals can also take important steps towards self-care.

  9. However, it is still possible to find outstanding values within the region itself.

  10. Even with the discussions of an agreement, the SEC is tightening the prerequisites needed for a company to pursue public status through a reverse merger.

  11. Conventional Lanna social construction continued principally unchanged for the reason that instances of authentic Lanna kingdom in the thirteenth century.

  12. Additional indicators exist to measure the sentiment specifically on Forex markets.

  13. It is also very important to choose an online licensed agency which will provide you with expert financial planners to help you invest your money in bonds wisely and carefully.

  14. In this article, we’ll sort through the mixed signals and see which types of exercise will help your heart the most and how much time you should spend at it.

  15. Postal Inspection Service (U.S.

  16. 東京空襲表示:

    This includes statutory laws concerned with the functioning of stock or securities markets (also see Security (finance), consumer and competition (antitrust) laws, labour or employment laws, and environmental protection laws, which may also entail disclosure requirements.

  17. You won’t solely get a hand on your favourite model and flaunt it amongst your buddy circle but additionally add a novel item to your gadget assortment.

  18. These actions can impression the corporate’s inventory price, as investors could view them as constructive or detrimental for the company’s lengthy-time period prospects.

  19. New businesses are a tremendous time commitment.

  20. コタツ 白表示:

    This means that buyers have been verified that they are capable of paying for the purchase, and vendors have received the payment in which it takes time.

  21. The absolute best investors may perhaps follow the day-to-day crisis of the markets, however they stick to the plan they created in calmer times and let tolerance, not panic, determine the long-term achievement of their investments.

  22. Sazrzbk表示:

    Купить диплом о среднем образовании в Москве и любом другом городе

    tosiya.ru/cb-profile/pluginclass/cbblogs?action=blogs&func=show&id=394

  23. Let’s take a look at what is likely to happen with players and discs as people upgrade.

  24. hlt 株価表示:

    In 1991 the venture capital industry invested approximately $2.2 billion in about 2,500 deals.

  25. McQueen maneuvers his way through a bad pile-up on the track to take the lead while The King and Chick Hicks make pit stops.

  26. For even more on the Ford Mustang, check out the following links.

  27. KevinSounc表示:

    http://slotsiteleri.bid/# slot siteleri guvenilir

  28. COMMERCIAL COMPANIES- these commercial companies trade minor quantities of foreign currencies compared to larger banks and their trades produce small and short-term impact on the market rates.

  29. A interval of sporadic tornadic activity affected the great Lakes, Higher Mississippi Valley, and the Mid-Atlantic starting on Could 18, when an EF0 twister precipitated tree damage near Rice Lake, Minnesota.

  30. At the time of his dying, Simons’s web value was estimated to be $31.4 billion, making him the 51st-richest individual in the world.

發佈留言

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