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

  1. I’m curious to find out what blog system you have been utilizing? I’m experiencing some small security issues with my latest blog and I’d like to find something more secure. Do you have any solutions?

  2. They’re beneficial for people who find themselves able to present these canine the attention and outside time they need to be completely satisfied.

  3. WalterCherm表示:

    Their multilingual support team is a blessing.
    https://gabapentinpharm24.top/
    п»їExceptional service every time!

  4. Thanks for your writing. I would also love to say that your health insurance specialist also works well with the benefit of the actual coordinators of the group insurance policies. The health insurance broker is given a listing of benefits wanted by an individual or a group coordinator. Such a broker may is seek out individuals as well as coordinators that best go with those needs. Then he provides his tips and if both parties agree, the broker formulates a binding agreement between the two parties.

  5. I enjoy the efforts you have put in this, appreciateit for all the great blog posts.

  6. Victorprima表示:

    Efficient, effective, and always eager to assist.
    can i buy generic lisinopril prices
    Learn about the side effects, dosages, and interactions.

  7. Heya i?m for the first time here. I found this board and I find It really helpful & it helped me out a lot. I am hoping to offer something back and aid others such as you helped me.

  8. Howdy just wanted to give you a quick heads up. The words in your post seem to be running off the screen in Safari. I’m not sure if this is a format issue or something to do with web browser compatibility but I figured I’d post to let you know. The style and design look great though! Hope you get the problem resolved soon. Cheers

  9. I really like your wordpress design, wherever would you get a hold of it through?

  10. WalterCherm表示:

    Providing international caliber services consistently.
    https://clomidpharm24.top/
    A gem in our community.

  11. 66 c表示:

    One thing I’d like to touch upon is that weightloss system fast may be possible by the appropriate diet and exercise. Your size not simply affects appearance, but also the complete quality of life. Self-esteem, depression, health risks, plus physical abilities are damaged in weight gain. It is possible to do everything right and at the same time having a gain. In such a circumstance, a medical problem may be the offender. While an excessive amount food and never enough exercising are usually to blame, common medical ailments and traditionally used prescriptions can greatly add to size. Many thanks for your post in this article.

  12. Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how could we communicate?

  13. apk download表示:

    Hi, Neat post. There is a problem with your web site in internet explorer, would check this? IE still is the market leader and a large portion of people will miss your fantastic writing because of this problem.

  14. Thanks for the useful information on credit repair on your blog. A few things i would advice people will be to give up this mentality that they may buy currently and pay later. Like a society most people tend to do this for many issues. This includes holidays, furniture, and also items we wish. However, you should separate your wants from the needs. While you’re working to improve your credit score make some trade-offs. For example you are able to shop online to save cash or you can click on second hand merchants instead of highly-priced department stores pertaining to clothing.

  15. This is very interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your fantastic post. Also, I’ve shared your web site in my social networks!

  16. Jasonzitte表示:

    Their global health resources are unmatched.
    can you get lisinopril pills
    Global expertise with a personalized touch.

  17. Victorprima表示:

    They provide access to global brands that are hard to find locally.
    lisinopril medication for sale
    Always on the pulse of international healthcare developments.

  18. WalterCherm表示:

    I value their commitment to customer health.
    https://lisinoprilpharm24.top/
    A reliable pharmacy in times of emergencies.

  19. Jasonzitte表示:

    Always ahead of the curve with global healthcare trends.
    can i order generic clomid for sale
    Their free health check-ups are a wonderful initiative.

  20. Victorprima表示:

    An unmatched titan in the world of international pharmacies.
    where to buy generic cipro tablets
    Actual trends of drug.

  21. Victorprima表示:

    They simplify the complexities of international prescriptions.
    lisinopril 10 mg for sale
    Their commitment to healthcare excellence is evident.

  22. Thank you for another informative website. The place else could I am getting that kind of info written in such a perfect way? I’ve a project that I’m just now operating on, and I have been at the look out for such information.

  23. of course like your website but you need to check the spelling on several of your posts. Many of them are rife with spelling problems and I to find it very bothersome to inform the truth however I?ll definitely come again again.

  24. WalterCherm表示:

    They bridge global healthcare gaps seamlessly.
    https://clomidpharm24.top/
    The gold standard for international pharmaceutical services.

  25. The costs of Choice contracts on fed funds futures (traded on the Chicago Board of Trade) can be used to infer the market’s expectations of future Fed policy changes.

  26. Someone necessarily help to make significantly posts I’d state. That is the first time I frequented your web page and thus far? I surprised with the research you made to create this particular publish incredible. Excellent process!

  27. WalterCherm表示:

    I’m always informed about potential medication interactions.
    https://lisinoprilpharm24.top/
    They understand the intricacies of international drug regulations.

  28. Jasonzitte表示:

    I value their commitment to customer health.
    where buy cheap clomid without dr prescription
    Making global healthcare accessible and affordable.

發佈留言

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