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

  1. Dino Game 119表示:

    Hi my friend! I want to say that this article is awesome, nice written and include approximately all vital infos. I?d like to see more posts like this.

  2. You could definitely see your enthusiasm in the work you write. The world hopes for even more passionate writers like you who are not afraid to say how they believe. Always follow your heart.

  3. Dino Game 129表示:

    I enjoy what you guys are usually up too. Such clever work and exposure! Keep up the awesome works guys I’ve you guys to blogroll.

  4. What i do not understood is in reality how you’re not really a lot more smartly-liked than you may be now. You’re very intelligent. You recognize thus significantly relating to this matter, made me in my view consider it from so many numerous angles. Its like men and women don’t seem to be interested unless it is one thing to do with Lady gaga! Your personal stuffs outstanding. Always maintain it up!

  5. The subsequent time I learn a weblog, I hope that it doesnt disappoint me as a lot as this one. I imply, I do know it was my option to learn, however I truly thought youd have something interesting to say. All I hear is a bunch of whining about something that you would repair if you werent too busy on the lookout for attention.

  6. Stephenzek表示:

    http://lisinopril.guru/# lisinopril 10 mg tablets price

  7. Stephenzek表示:

    https://furosemide.win/# lasix uses

  8. Howdy! Someone in my Myspace group shared this website with us so I came to check it out. I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers! Outstanding blog and wonderful design.

  9. Mvuqhg表示:

    buy generic besifloxacin – sildamax pills buy sildamax pills for sale

  10. Dino Game 123表示:

    Hmm it appears 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 too am an aspiring blog writer but I’m still new to the whole thing. Do you have any recommendations for rookie blog writers? I’d really appreciate it.

  11. Dino Game 120表示:

    My brother recommended I might like this blog. He was entirely right. This post actually made my day. You cann’t imagine just how much time I had spent for this information! Thanks!

  12. One thing I would like to say is the fact before obtaining more laptop memory, look into the machine into which it would be installed. Should the machine will be running Windows XP, for instance, the particular memory ceiling is 3.25GB. Setting up more than this would easily constitute a new waste. Make certain that one’s motherboard can handle this upgrade quantity, as well. Thanks for your blog post.

  13. I absolutely love your blog and find a lot of your post’s to be just what I’m looking for. Would you offer guest writers to write content available for you? I wouldn’t mind creating a post or elaborating on a number of the subjects you write with regards to here. Again, awesome website!

  14. Dnrtjtv表示:

    Добрый день!
    Купить документ о получении высшего образования вы имеете возможность в нашей компании.
    ba.rolka.me/viewtopic.php?id=15483#p18803

  15. Dino Game 126表示:

    Good post. I be taught something tougher on totally different blogs everyday. It will always be stimulating to read content from different writers and follow a bit of something from their store. I?d prefer to use some with the content material on my weblog whether you don?t mind. Natually I?ll give you a hyperlink on your internet blog. Thanks for sharing.

  16. Wow that was unusual. I just wrote an incredibly long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say wonderful blog!

  17. I think this is among the most vital info for me. And i’m glad reading your article. But should remark on some general things, The site style is great, the articles is really nice : D. Good job, cheers

  18. I’m so 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.

  19. Hello there, You have done an excellent job. I will definitely digg it and in my opinion recommend to my friends. I am sure they’ll be benefited from this web site.

  20. Excellent post. I was checking continuously this weblog and I am inspired! Extremely helpful information specially the ultimate section 🙂 I deal with such information much. I was seeking this certain information for a long time. Thank you and good luck.

  21. Most of what you claim happens to be supprisingly precise and it makes me wonder the reason why I had not looked at this with this light previously. This particular piece really did switch the light on for me as far as this particular subject matter goes. Nonetheless at this time there is actually one particular issue I am not really too cozy with so whilst I attempt to reconcile that with the central theme of the point, allow me see what all the rest of the visitors have to point out.Nicely done.

  22. I?ve recently started a blog, the information you provide on this website has helped me tremendously. Thanks for all of your time & work.

  23. I?ll right away take hold of your rss as I can not to find your e-mail subscription link or newsletter service. Do you’ve any? Kindly allow me recognize in order that I may just subscribe. Thanks.

  24. Stephenzek表示:

    https://tamoxifen.bid/# tamoxifen for men

  25. Do you have a spam issue on this site; I also am a blogger, and I was curious about your situation; many of us have created some nice practices and we are looking to swap methods with others, why not shoot me an email if interested.

  26. Jamesric表示:

    tamoxifen adverse effects: Purchase Nolvadex Online – pct nolvadex

  27. Jamesric表示:

    lipitor 20 mg price in india: lipitor simvastatin – lipitor 80 mg daily

  28. Thanks for your post. I also believe that laptop computers are getting to be more and more popular right now, and now are often the only form of computer utilised in a household. The reason is that at the same time potentially they are becoming more and more affordable, their processing power is growing to the point where they may be as potent as desktop computers coming from just a few years ago.

發佈留言

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