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

37,436 Responses

  1. MichaelLoapy表示:

    best rated canadian pharmacy Express Rx Canada canadian pharmacy ed medications

  2. StevenDuase表示:

    legitimate canadian pharmacies: trustworthy canadian pharmacy – the canadian drugstore

  3. StevenDuase表示:

    indian pharmacy: indianpharmacy com – medicine courier from India to USA

  4. Michaelrom表示:

    indian pharmacy: indian pharmacy online – MedicineFromIndia

  5. Dannytal表示:

    indian pharmacy: MedicineFromIndia – Medicine From India

  6. WalterIcort表示:

    https://expressrxcanada.com/# buying drugs from canada

  7. Dannytal表示:

    Rx Express Mexico: Rx Express Mexico – mexican online pharmacies prescription drugs

  8. 868vip表示:

    I have noticed that over the course of building a relationship with real estate proprietors, you’ll be able to get them to understand that, in each and every real estate exchange, a fee is paid. In the long run, FSBO sellers don’t “save” the commission. Rather, they fight to earn the commission by way of doing an agent’s task. In doing this, they invest their money in addition to time to conduct, as best they are able to, the responsibilities of an real estate agent. Those assignments include uncovering the home by means of marketing, delivering the home to all buyers, constructing a sense of buyer urgency in order to trigger an offer, making arrangement for home inspections, controlling qualification inspections with the loan provider, supervising maintenance, and assisting the closing of the deal.

  9. alo789表示:

    This is hands down one of the best articles I’ve read on this topic! The author’s thorough knowledge and enthusiasm for the subject are evident in every paragraph. I’m so thankful for finding this piece as it has deepened my comprehension and stimulated my curiosity even further. Thank you, author, for investing the time to create such a outstanding article!

  10. WalterIcort表示:

    http://medicinefromindia.com/# indian pharmacy online

  11. MichaelLoapy表示:

    reputable canadian pharmacy ExpressRxCanada is canadian pharmacy legit

  12. Download now表示:

    Wonderful beat ! I would like to apprentice while you amend your web site, how can i subscribe for a weblog site? The account aided me a applicable deal. I have been tiny bit acquainted of this your broadcast provided bright clear idea

  13. Explore表示:

    I just couldn’t depart your web site prior to suggesting that I really enjoyed the standard information a person provide for your visitors? Is gonna be back often in order to check up on new posts

  14. StevenDuase表示:

    indian pharmacy: MedicineFromIndia – Medicine From India

  15. MichaelLoapy表示:

    canadian pharmacy com Generic drugs from Canada best canadian pharmacy

  16. Dannytal表示:

    canadian pharmacy online ship to usa: Generic drugs from Canada – canadian medications

  17. We are searching for some people that are interested in from working their home on a part-time basis. If you want to earn $100 a day, and you don’t mind developing some short opinions up, this is the perfect opportunity for you!

  18. WalterIcort表示:

    https://rxexpressmexico.shop/# Rx Express Mexico

  19. alo789表示:

    I have observed that in cameras, extraordinary detectors help to {focus|concentrate|maintain focus|target|a**** automatically. The particular sensors connected with some digital cameras change in in the area of contrast, while others start using a beam of infra-red (IR) light, particularly in low light. Higher standards cameras occasionally use a mixture of both programs and could have Face Priority AF where the camera can ‘See’ the face and focus only in that. Many thanks for sharing your thinking on this web site.

  20. MichaelLoapy表示:

    Rx Express Mexico mexican rx online mexico pharmacy order online

  21. alo789表示:

    Thanks for revealing your ideas in this article. The other point is that when a problem arises with a computer system motherboard, people today should not consider the risk connected with repairing the item themselves for if it is not done properly it can lead to irreparable damage to the whole laptop. It is usually safe just to approach the dealer of your laptop for any repair of the motherboard. They’ve got technicians who may have an experience in dealing with pc motherboard challenges and can make the right diagnosis and perform repairs.

  22. Uthtxp表示:

    order meloxicam 15mg – buy flomax pill order tamsulosin 0.4mg generic

  23. Michaelrom表示:

    canadianpharmacymeds: Express Rx Canada – canadian mail order pharmacy

  24. Buy now表示:

    Thanks for another excellent post. Where else could anyone get that kind of information in such an ideal way of writing? I’ve a presentation next week, and I am on the look for such information.

  25. MichaelLoapy表示:

    best online pharmacies in mexico mexican online pharmacy Rx Express Mexico

  26. gvui表示:

    I am really impressed together with your writing abilities as well as with the layout on your weblog. Is that this a paid theme or did you customize it yourself? Either way keep up the excellent high quality writing, it is rare to see a great blog like this one these days..

  27. Michaelrom表示:

    canadian online drugstore: canada drug pharmacy – canadian pharmacy reviews

  28. Timastus表示:

    безопасная сделка аккаунтов аккаунты с балансом

  29. StevenDuase表示:

    medicine courier from India to USA: indian pharmacy online shopping – Medicine From India

發佈回覆給「WalterIcort」的留言 取消回覆

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