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

  1. This amount will most likely be reversed once the real public sale bills are debited out of your account.

  2. The Subprime mortgage disaster options debate discusses various actions and proposals by economists, authorities officials, journalists, and enterprise leaders to handle the subprime mortgage disaster and broader 2007-2008 financial crisis.

  3. MauriceGueda表示:

    rx to go pharmacy: care rx pharmacy tallahassee fl – giant food store pharmacy

  4. CSAs have even grow to be widespread in city environments equivalent to the brand new York City Coalition In opposition to Hunger’s CSA program that helps serve beneath-served communities.

  5. Different states, together with Georgia, offer non-monetary incentives like free use of excessive-occupancy vehicle (HOV) lanes, whatever the number of passengers within the vehicle.

  6. 35 ドル 円表示:

    34.Three billion in U.S.

  7. MauriceGueda表示:

    online pharmacy india: online pharmacy india – reputable indian online pharmacy

  8. почва грунт для цветов http://dachnik18.ru/ .

  9. The metropolitan area of Chennai covers many suburbs which can be a part of Chengalpattu, Kanchipuram and Thiruvallur districts.

  10. This doc proposes that New Zealand proceed with the implementation of Normal Enterprise Reporting (SBR) as an entire-of-government work programme aimed at decreasing reporting prices, and thereby compliance costs, for business.

  11. 株価 pff表示:

    Thus, where the shopper realizes long-term capital features, the manager’s acquire is a long-time period capital gain-usually leading to a lower tax rate for the manager than can be the case if the manager’s revenue were not treated as a long-time period capital acquire.

  12. With the introduction of obligatory army service in 1935, the Reichswehr, which had been restricted to 100,000 by the terms of the Versailles Treaty, expanded to 750,000 on lively service initially of World Warfare II, with 1,000,000 more in the reserve.

  13. In March 2008, Starbucks introduced its buy of the Espresso Gear Company.

  14. It was at this point that Northwest started painting its airliners’ tails brilliant red as a visible aid within the typically harsh weather conditions.

  15. All the prospectuses as well as some other related paperwork which have to be duly filed, accomplished as well as distributed are ensured by the fund supervisor as nicely.

  16. 久留米市 職員 不祥事表示:

    Finally, 8,500 folks evacuated prior to the storm’s arrival, including 2,600 in Cabo Corrientes.

  17. One other embedded EF2 twister touched down east of Lake Scugog and passed close to the rural communities of Janetville and Yelverton, damaging or destroying a number of outbuildings, barns, and machine sheds.

  18. Отличный сайт! Всем рекомендую!оптика Москва

  19. SureTec Financial Corp., one in all the most important privately owned surety firms within the US.

  20. Kqpjml表示:

    diclofenac cost – nimodipine brand buy cheap generic nimodipine

  21. Josephfub表示:

    pharmacy artane benadryl boots pharmacy prices pharmacy

  22. Throughout the affected area, the storm’s powerful winds left 261,989 folks with out electricity.

  23. This portable machine was a digicam, movie processing lab and projector multi functional package deal!

  24. Josephfub表示:

    viagra apollo pharmacy phenytoin pharmacy protocol rx unlimited pharmacy

  25. ArthurKib表示:

    https://mexicopharmacy.cheap/# medicine in mexico pharmacies

  26. Con᠎tent h​as  be᠎en gener at᠎ed by G SA Con te᠎nt G en​erat or Demov​er sion !

  27. Though the stock has ended on a whimper, 2010 has given Akamai investors motive to shout for joy.

  28. Often you can put in as much as 15 percent of your annual salary.

  29. Josephfub表示:

    Online medicine home delivery mail order pharmacy india india online pharmacy

發佈留言

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