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

  1. Thank you for the sensible critique. Me & my neighbor were just preparing to do a little research about this. We got a grab a book from our local library but I think I learned more clear from this post. I’m very glad to see such great info being shared freely out there.

  2. It’s a shame you don’t have a donate button! I’d without a doubt donate to this excellent blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to new updates and will talk about this blog with my Facebook group. Talk soon!

  3. With havin so much written content do you ever run into any problems of plagorism or copyright infringement? My website has a lot of unique content I’ve either authored myself or outsourced but it looks like a lot of it is popping it up all over the internet without my agreement. Do you know any ways to help reduce content from being ripped off? I’d really appreciate it.

  4. Hello, i think that i saw you visited my weblog thus i came to ?return the desire?.I’m attempting to find issues to enhance my website!I suppose its ok to make use of a few of your ideas!!

  5. noey atc表示:

    Undeniably believe that which you said. Your favorite reason seemed to be on the web the simplest thing to be aware of. I say to you, I definitely get irked while people think about worries that they just do not know about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people can take a signal. Will probably be back to get more. Thanks

  6. I’ve observed that in the world nowadays, video games include the latest rage with children of all ages. Often times it may be extremely hard to drag your son or daughter away from the activities. If you want the best of both worlds, there are numerous educational gaming activities for kids. Good post.

  7. Hi! I just wanted to ask if you ever have any issues with hackers? My last blog (wordpress) was hacked and I ended up losing several weeks of hard work due to no data backup. Do you have any solutions to prevent hackers?

  8. Whats up very nice web site!! Man .. Beautiful .. Superb .. I will bookmark your website and take the feeds also?I am happy to find so many useful information here in the submit, we’d like work out extra strategies in this regard, thank you for sharing. . . . . .

  9. WayneCoirl表示:

    purple pharmacy mexico price list: medicine in mexico pharmacies – mexican mail order pharmacies

  10. DominicJaw表示:

    mexican rx online: mexican drugstore online – mexican pharmaceuticals online

  11. Aw, this was a very nice post. In concept I would like to put in writing like this additionally ? taking time and actual effort to make a very good article? but what can I say? I procrastinate alot and by no means seem to get one thing done.

  12. скачать порно коллекций https://www.porn-library.ru .

  13. It’s appropriate time to make some plans for the future and it’s time to be happy. I have read this post and if I could I desire to suggest you some interesting things or suggestions. Maybe you could write next articles referring to this article. I want to read even more things about it!

  14. magnificent post, very informative. I wonder why the other experts of this sector do not notice this. You must continue your writing. I’m confident, you’ve a huge readers’ base already!

  15. Nelsonbluck表示:

    pharmacies in mexico that ship to usa: mexico drug stores pharmacies – mexican pharmaceuticals online

  16. Arnoldten表示:

    mexico pharmacies prescription drugs buying prescription drugs in mexico mexican pharmacy

  17. Thanks , I’ve just been looking for information about this topic for ages and yours is the greatest I’ve discovered so far. But, what about the conclusion? Are you sure about the source?

  18. There is noticeably a bundle to learn about this. I assume you made sure nice points in options also.

  19. Simply desire to say your article is as amazing. The clarity to your publish is just great and i can assume you are an expert on this subject. Fine along with your permission let me to grab your feed to stay up to date with impending post. Thank you one million and please carry on the gratifying work.

  20. Hmm it seems like your blog ate my first comment (it was super long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to the whole thing. Do you have any suggestions for beginner blog writers? I’d really appreciate it.

  21. whoah this blog is great i love reading your posts. Keep up the good work! You know, lots of people are searching around for this info, you could aid them greatly.

  22. RichardWrifs表示:

    http://mexicandeliverypharma.com/# mexico drug stores pharmacies

  23. An added important issue is that if you are a mature person, travel insurance pertaining to pensioners is something you should make sure you really contemplate. The old you are, the harder at risk you happen to be for having something bad happen to you while abroad. If you are definitely not covered by many comprehensive insurance plan, you could have a few serious troubles. Thanks for discussing your ideas on this weblog.

  24. Heya i?m for the first time here. I found this board and I find It really useful & it helped me out a lot. I hope to give something back and help others like you helped me.

  25. The next time I read a weblog, I hope that it doesnt disappoint me as a lot as this one. I imply, I do know it was my choice to learn, but I really thought youd have something interesting to say. All I hear is a bunch of whining about something that you could possibly repair in case you werent too busy looking for attention.

  26. Thanks, I’ve been hunting for information about this topic for ages and yours is the best I have discovered so far.

  27. WayneCoirl表示:

    purple pharmacy mexico price list: mexican rx online – medicine in mexico pharmacies

  28. DominicJaw表示:

    reputable mexican pharmacies online: reputable mexican pharmacies online – buying prescription drugs in mexico online

  29. Nice blog right here! Also your website quite a bit up very fast! What web host are you using? Can I am getting your associate hyperlink to your host? I wish my site loaded up as fast as yours lol

  30. Amazing! This blog looks exactly like my old one! It’s on a completely different subject but it has pretty much the same layout and design. Excellent choice of colors!

發佈留言

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