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

16,073 Responses

  1. Currently it looks like WordPress is the best blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?

  2. Thanks for the concepts you are sharing on this website. Another thing I want to say is that getting hold of copies of your credit rating in order to scrutinize accuracy of the detail is the first measures you have to execute in fixing credit. You are looking to freshen your credit profile from destructive details mistakes that ruin your credit score.

  3. Heya i am for the first time here. I came across this board and I to find It truly helpful & it helped me out a lot. I am hoping to offer something back and help others such as you helped me.

  4. I have been absent for some time, but now I remember why I used to love this web site. Thank you, I?ll try and check back more often. How frequently you update your website?

  5. ever night表示:

    I’ve learned newer and more effective things through the blog post. One more thing to I have noticed is that in most cases, FSBO sellers can reject an individual. Remember, they would prefer to not ever use your expert services. But if you actually maintain a comfortable, professional relationship, offering assistance and remaining in contact for four to five weeks, you will usually be capable to win interviews. From there, a house listing follows. Thanks a lot

  6. Awesome blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog stand out. Please let me know where you got your design. Kudos

  7. Hiya, I’m really glad I’ve found this info. Nowadays bloggers publish only about gossips and net and this is really irritating. A good website with interesting content, this is what I need. Thanks for keeping this site, I’ll be visiting it. Do you do newsletters? Can not find it.

  8. I?ll right away grasp your rss feed as I can not to find your email subscription link or e-newsletter service. Do you have any? Kindly allow me know so that I could subscribe. Thanks.

  9. Thanks for your recommendations on this blog. 1 thing I would want to say is purchasing consumer electronics items from the Internet is certainly not new. Actually, in the past few years alone, the marketplace for online electronics has grown drastically. Today, you’ll find practically virtually any electronic gizmo and product on the Internet, ranging from cameras plus camcorders to computer pieces and gaming consoles.

  10. I do enjoy the manner in which you have framed this specific matter plus it does indeed offer me some fodder for thought. However, coming from what precisely I have experienced, I simply hope when other feedback pack on that people today stay on issue and don’t get started upon a tirade regarding the news du jour. Still, thank you for this superb point and though I can not necessarily agree with this in totality, I respect the standpoint.

  11. It’s a shame you don’t have a donate button! I’d certainly donate to this brilliant blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to new updates and will share this blog with my Facebook group. Talk soon!

  12. Thank you for some other great post. The place else may just anyone get that kind of info in such a perfect way of writing? I have a presentation subsequent week, and I am on the look for such information.

  13. I’m not that much of a online reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your site to come back later on. Many thanks

  14. whoah this blog is great i love studying your articles. Keep up the good paintings! You know, many people are hunting around for this information, you could aid them greatly.

  15. I am very happy to read this. This is the type of manual that needs to be given and not the random misinformation that’s at the other blogs. Appreciate your sharing this best doc.

  16. I just like the helpful info you supply in your articles. I will bookmark your blog and test again right here regularly. I am moderately certain I?ll be informed many new stuff right here! Best of luck for the following!

  17. Excellent site you have here but I was curious about if you knew of any community forums that cover the same topics discussed here? I’d really love to be a part of online community where I can get feedback from other knowledgeable people that share the same interest. If you have any suggestions, please let me know. Thanks!

  18. Wow, this article is mind-blowing! The author has done a tremendous job of delivering the information in an compelling and enlightening manner. I can’t thank her enough for sharing such priceless insights that have undoubtedly enlightened my knowledge in this subject area. Hats off to her for producing such a gem!

  19. срочный вывод из запоя на дому недорого срочный вывод из запоя на дому недорого .

  20. of fuyao表示:

    okmark your weblog and check again here frequently. I’m quite sure I will learn many new stuff right here! Best of luck for the next!

  21. Great web site. Plenty of useful information here. I am sending it to some friends ans also sharing in delicious. And naturally, thanks for your sweat!

  22. Hey very cool web site!! Man .. Excellent .. Wonderful .. I will bookmark your web site and take the feeds also?I’m satisfied to search out numerous useful info right here within the publish, we need work out more strategies in this regard, thank you for sharing. . . . . .

  23. With havin so much written content do you ever run into any issues of plagorism or copyright infringement? My website has a lot of completely unique content I’ve either created myself or outsourced but it looks like a lot of it is popping it up all over the web without my agreement. Do you know any ways to help protect against content from being ripped off? I’d genuinely appreciate it.

  24. Trefjai表示:

    Здравствуйте!
    Легальные способы покупки диплома о среднем полном образовании
    bank-garantiya.ru/index.php?subaction=userinfo&user=elotomyp
    Поможем вам всегда!.

  25. Do you have a spam problem on this site; I also am a blogger, and I was wanting to know your situation; many of us have created some nice practices and we are looking to exchange techniques with others, why not shoot me an e-mail if interested.

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

  27. Somebody essentially assist to make significantly posts I might state. This is the first time I frequented your website page and so far? I amazed with the analysis you made to make this actual publish incredible. Magnificent job!

  28. Wonderful blog! I found it while browsing on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Cheers

  29. Wow! I’m in awe of the author’s writing skills and talent to convey complex concepts in a straightforward and clear manner. This article is a real treasure that deserves all the applause it can get. Thank you so much, author, for offering your knowledge and offering us with such a valuable treasure. I’m truly thankful!

  30. Thanks for another magnificent post. The place else may anybody get that type of information in such a perfect method of writing? I’ve a presentation next week, and I am on the search for such info.

發佈留言

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