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

  1. บลีช表示:

    Valuable information. Lucky me I found your site by accident, and I am shocked why this accident did not happened earlier! I bookmarked it.

  2. Thanks for expressing your ideas. I’d personally also like to state that video games have been actually evolving. Better technology and inventions have made it simpler to create realistic and fun games. These kinds of entertainment games were not really sensible when the real concept was first of all being attempted. Just like other styles of technology, video games also have had to progress as a result of many generations. This is testimony for the fast continuing development of video games.

  3. If you are heading in it as a full time job, you have to be on your toes.

  4. Howdy! Someone in my Facebook group shared this website with us so I came to give it a look. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers! Fantastic blog and excellent design.

  5. Looking at the world of wine from a 21st-century perspective, it’s easy to forget that American wines (for this piece we’re limiting that to U.S.

  6. The base model started at $9,000, which is the equivalent of around $128,000 in today’s dollars – a true status symbol in an economically devastated market.

  7. Aw, this was a very nice post. In idea 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 in no way seem to get something done.

  8. It can take many months or years before the investment generates sufficient return to pay back its cost, and hence the finance is long term.

  9. LewisTwera表示:

    http://cytotecbestprice.pro/# buy cytotec pills online cheap

  10. You really make it appear so easy with your presentation however I in finding this topic to be actually something that I believe I’d never understand. It seems too complex and very extensive for me. I’m looking forward in your next post, I?ll try to get the cling of it!

  11. conan表示:

    I have seen plenty of useful issues on your web page about pcs. However, I’ve the impression that lap tops are still less than powerful sufficiently to be a good choice if you usually do tasks that require plenty of power, like video editing and enhancing. But for web surfing, word processing, and the majority of other common computer work they are perfectly, provided you can’t mind the tiny screen size. Many thanks sharing your opinions.

  12. You must take part in a contest for the most effective blogs on the web. I will recommend this site!

  13. Sazrtaa表示:

    Привет!
    Диплом экономиста
    njt.ru/forum/user/197785

  14. I’m not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your website to come back down the road. All the best

  15. PatrickTig表示:

    http://nolvadexbestprice.pro/# raloxifene vs tamoxifen

  16. Matthewchact表示:

    п»їcytotec pills online: buy misoprostol over the counter – order cytotec online

  17. I’ve been surfing online greater than 3 hours these days, but I never discovered any fascinating article like yours. It is beautiful price sufficient for me. In my view, if all website owners and bloggers made good content material as you did, the net will likely be a lot more useful than ever before.

  18. RobertSic表示:

    hysterectomy after breast cancer tamoxifen nolvadex only pct alternative to tamoxifen

  19. Great weblog right here! Also your web site so much up very fast! What host are you the use of? Can I am getting your associate link to your host? I desire my web site loaded up as fast as yours lol

  20. blue exorcist表示:

    I do like the way you have presented this challenge and it does indeed supply us some fodder for consideration. However, through what I have personally seen, I simply just wish when the feedback stack on that individuals remain on point and not embark upon a tirade associated with the news du jour. Still, thank you for this outstanding piece and although I can not go along with this in totality, I regard the point of view.

  21. Wonderful site. A lot of helpful information here. I?m sending it to several pals ans also sharing in delicious. And of course, thanks in your effort!

  22. Hey there! This is my 1st comment here so I just wanted to give a quick shout out and say I genuinely enjoy reading your posts. Can you recommend any other blogs/websites/forums that go over the same subjects? Many thanks!

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

  24. Mazrukq表示:

    Привет, друзья!
    Возможно ли купить диплом стоматолога, и как это происходит
    rushkadiplomik.ru

  25. you may have an ideal weblog right here! would you like to make some invite posts on my weblog?

  26. Have you ever thought about creating an e-book or guest authoring on other websites? I have a blog based upon on the same topics you discuss and would really like to have you share some stories/information. I know my audience would appreciate your work. If you are even remotely interested, feel free to shoot me an e-mail.

  27. LewisTwera表示:

    https://nolvadexbestprice.pro/# how to get nolvadex

  28. Thank you for every other fantastic post. The place else may just anybody get that type of information in such a perfect approach of writing? I’ve a presentation subsequent week, and I am at the search for such info.

  29. Via my observation, shopping for electronic products online can for sure be expensive, nonetheless there are some how-to’s that you can use to obtain the best products. There are continually ways to find discount specials that could make one to have the best electronics products at the lowest prices. Thanks for your blog post.

  30. wonderful post, very informative. I wonder why the other experts of this sector don’t notice this. You should continue your writing. I’m confident, you have a great readers’ base already!

發佈留言

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