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

11,031 Responses

  1. I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to create my own blog and would like to find out where u got this from. thanks a lot

  2. It is essential that you search for the best expert help you can manage.

  3. I believe that is one of the such a lot important info for me. And i am glad reading your article. However wanna commentary on some general issues, The web site style is perfect, the articles is in reality excellent : D. Excellent task, cheers

  4. Can I simply say what a relief to find somebody who actually knows what theyre speaking about on the internet. You positively know learn how to deliver a difficulty to light and make it important. Extra individuals need to learn this and perceive this side of the story. I cant imagine youre no more fashionable because you undoubtedly have the gift.

  5. I really like your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to design my own blog and would like to find out where u got this from. thanks a lot

  6. I just couldn’t depart your web site prior to suggesting that I extremely loved the usual info a person provide for your visitors? Is going to be again frequently in order to check up on new posts

  7. I?d should verify with you here. Which isn’t something I normally do! I enjoy reading a put up that may make individuals think. Also, thanks for allowing me to comment!

  8. Awesome blog! Do you have any tips for aspiring writers? I’m planning to start my own site soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely overwhelmed .. Any tips? Cheers!

  9. hello!,I like your writing very much! share we keep in touch more approximately your article on AOL? I require a specialist on this area to resolve my problem. Maybe that is you! Taking a look ahead to look you.

  10. I’ve been surfing online more than three hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my opinion, if all website owners and bloggers made good content as you did, the internet will be much more useful than ever before.

  11. Good day! I just want to give a huge thumbs up for the great data you’ve here on this post. I will probably be coming back to your weblog for extra soon.

  12. game 2023表示:

    This will be a great website, would you be involved in doing an interview about just how you created it? If so e-mail me!

  13. Using technology, businesses can reach a large number of customers with minimal costs.

  14. By investing in PE, the investor can ensure the chances to generate higher absolute returns while improving the diversification portfolio.

  15. I truly appreciate this post. I have been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thank you again

  16. Thanks for the unique tips discussed on this blog site. I have seen that many insurers offer customers generous deals if they prefer to insure more and more cars together. A significant volume of households own several cars or trucks these days, especially those with mature teenage youngsters still residing at home, and also the savings for policies can soon increase. So it pays off to look for a great deal.

  17. Thanks for another informative website. The place else could I get that kind of information written in such an ideal manner? I have a project that I am just now working on, and I have been at the glance out for such information.

  18. Thanks for the ideas you talk about through this web site. In addition, many young women who seem to become pregnant tend not to even try to get health care insurance because they fear they might not qualify. Although some states at this moment require that insurers provide coverage no matter the pre-existing conditions. Fees on these types of guaranteed programs are usually higher, but when considering the high cost of medical care it may be a new safer approach to take to protect your financial future.

  19. Thank you for another fantastic article. Where else may just anyone get that kind of info in such a perfect way of writing? I’ve a presentation subsequent week, and I am at the search for such info.

  20. Feel free to visit my site :: high stake poker

  21. Stephenzek表示:

    https://cytotec.pro/# buy cytotec in usa

  22. Thank you for another informative blog. Where else could I get that type of info written in such a perfect way? I have a project that I am just now working on, and I have been on the look out for such info.

  23. Better yet, think substitution, not elimination.

  24. Hi there! Do you use Twitter? I’d like to follow you if that would be ok. I’m absolutely enjoying your blog and look forward to new updates.

  25. I’ve really noticed that fixing credit activity has to be conducted with techniques. If not, you might find yourself damaging your standing. In order to realize your aspirations in fixing your credit ranking you have to confirm that from this time you pay your entire monthly costs promptly prior to their timetabled date. It’s really significant since by certainly not accomplishing so, all other moves that you will decide on to improve your credit standing will not be helpful. Thanks for discussing your ideas.

  26. I know this if off topic but I’m looking into starting my own blog and was wondering what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web savvy so I’m not 100 certain. Any recommendations or advice would be greatly appreciated. Many thanks

  27. What i do not realize is actually how you’re not actually much more well-liked than you may be now. You are very intelligent. You realize thus significantly relating to this subject, made me personally consider it from a lot of varied angles. Its like men and women aren’t fascinated unless it is one thing to accomplish with Lady gaga! Your own stuffs nice. Always maintain it up!

  28. Simply desire to say your article is as amazing. The clearness in your post is just excellent and i could assume you are an expert on this subject. Well with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please keep up the rewarding work.

  29. Superb blog! Do you have any suggestions for aspiring writers? I’m planning to start my own website soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely confused .. Any suggestions? Thank you!

發佈留言

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