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

  1. Nonetheless, in addition to this, the investor has the opportunity of buying or promoting the ETF, in the same style to open-end mutual funds (funds that aren’t listed on TASE).

  2. RobertMef表示:

    top online pharmacy india: india pharmacy – india pharmacy mail order

  3. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: ремонт бытовой техники в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  4. AFOSR is primarily a funding physique for exterior analysis while the other directorates perform analysis in-house or below contract to external entities.

  5. After you’ve bought an thought of what kind of residence you’ll be able to afford, ensure you plan.

  6. In the next part, we’ll try a few of what goes on the behind the scenes to make Digg work.

  7. RobertMef表示:

    viagra pharmacy: zithromax prices pharmacy – simvastatin uk pharmacy

  8. NWS Harm Survey for 05/12/22 Tornado Event (Report).

  9. The Economist. 14 December 1996.

  10. Whiteboard markers are straightforward to erase using a soft cloth or even tissue paper.

  11. 40 and 50 flights per day (about 2 of complete day by day flights) throughout September and October 2017.

  12. Estimates of the infant mortality price range from 57 to seventy four deaths/1,000 reside births.

  13. A few of the most important places of work in the IFSC are these of the major Irish accounting and law corporations.

  14. It also makes artificial foliage extra workable.C.

  15. Nigel Goldenfeld, a professor of physics at College of Illinois, recommends Chriss’s e book Black-Scholes and Beyond to those of his college students “contemplating a profession in quantitative finance”, as giving an “Excellent overview of modern-day finance, financial models, and their shortcomings. An incredible mix of sensible and theoretical data, clearly presented”.

  16. At the closing, you and the sellers — along with your real property brokers — will meet in a convention room to signal the biggest stack of papers you’ve ever seen.

  17. Every year, a motorcade is staged, by which gamers who’ve retired because the previous grand remaining are given a lap of honour in open high vehicles.

  18. This implies that each working individual will help an average of 1.Four heads as dependent.

  19. RobertMef表示:

    buy medicines online in india: india online pharmacy – indian pharmacy online

  20. biardiova表示:

    Aromatase activity was determined using the tritiated water release method developed by Thompson and Siiteri 23 priligy tablets online

  21. Josephfub表示:

    Tenoretic 100mg ketoconazole shampoo pharmacy the drug store pharmacy

  22. Josephfub表示:

    men’s health online pharmacy certification best rx pharmacy port charlotte fl

  23. Josephfub表示:

    people’s pharmacy generic wellbutrin ivermectin pharmacy online pharmacy store hyderabad

  24. MauriceGueda表示:

    buy medicines online in india: reputable indian pharmacies – indian pharmacy online

  25. ArthurKib表示:

    https://pharmbig24.com/# escrow pharmacy online

  26. ArthurKib表示:

    https://mexicopharmacy.cheap/# mexican rx online

  27. MauriceGueda表示:

    mexico drug stores pharmacies: mexican mail order pharmacies – п»їbest mexican online pharmacies

  28. RobertMef表示:

    buying prescription drugs in mexico: pharmacies in mexico that ship to usa – mexican border pharmacies shipping to usa

  29. MauriceGueda表示:

    playa del carmen pharmacy viagra: misoprostol pharmacy – pharmacy viagra malaysia

  30. RobertMef表示:

    mexican online pharmacies prescription drugs: mexican pharmaceuticals online – п»їbest mexican online pharmacies

發佈留言

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