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

10,500 Responses

  1. Thanks for the thoughts you are revealing on this web site. Another thing I would really like to say is that often getting hold of copies of your credit file in order to examine accuracy of each and every detail could be the first step you have to conduct in repairing credit. You are looking to clean up your credit history from damaging details problems that spoil your credit score.

  2. Woah! I’m really enjoying the template/theme of this blog. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between user friendliness and visual appearance. I must say you have done a excellent job with this. Additionally, the blog loads very fast for me on Internet explorer. Exceptional Blog!

  3. RWC Melbourne表示:

    Do you mind if I quote a few of your articles as long as I provide credit and sources back to your webpage? My blog site is in the exact same niche as yours and my users would really benefit from some of the information you present here. Please let me know if this alright with you. Appreciate it!

  4. Thanks for expressing your ideas. One thing is that pupils have an alternative between federal student loan plus a private education loan where it can be easier to go with student loan debt consolidation loan than with the federal education loan.

  5. This site is really a walk-by means of for the entire information you wished about this and didn?t know who to ask. Glimpse right here, and you?ll definitely discover it.

  6. Отличный сайт! Всем рекомендую!Воздушные шары

  7. I really like your wordpress template, exactly where did you down load it through?

  8. Someone essentially help to make seriously articles I would state. This is the very first time I frequented your web page and thus far? I surprised with the research you made to make this particular publish extraordinary. Fantastic job!

  9. Hey there, I think your site might be having browser compatibility issues. When I look at your blog site in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, excellent blog!

  10. Jogue no cassino de maior prestigio Blaze

  11. Hmm it looks like your website ate my first comment (it was super long) so I guess I’ll just sum it up what I had written 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 tips and hints for inexperienced blog writers? I’d really appreciate it.

  12. Bbkatz表示:

    buy depakote 500mg without prescription – depakote where to buy buy generic topiramate 200mg

  13. Thank you for another great post. Where else could anyone get that kind of info in such a perfect way of writing? I have a presentation next week, and I’m on the look for such info.

  14. Thanks for your post. What I want to comment on is that when you are evaluating a good internet electronics retail outlet, look for a web site with total information on key elements such as the security statement, security details, payment procedures, and other terms plus policies. Generally take time to investigate the help plus FAQ sections to get a greater idea of how the shop functions, what they are able to do for you, and ways in which you can use the features.

  15. Thanks for your post. I also believe laptop computers have grown to be more and more popular lately, and now in many cases are the only sort of computer utilized in a household. Simply because at the same time actually becoming more and more economical, their working power keeps growing to the point where there’re as highly effective as pc’s coming from just a few in years past.

  16. okmark your weblog and check again here regularly. I’m quite certain I will learn many new stuff right here! Good luck for the next!

  17. It is actually a nice and useful piece of information. I?m glad that you simply shared this useful info with us. Please keep us up to date like this. Thank you for sharing.

  18. Hi, I think your site might be having browser compatibility issues. When I look at your blog in Ie, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, superb blog!

  19. Hiya, I am really glad I’ve found this information. Today bloggers publish only about gossips and net and this is actually frustrating. A good blog with interesting content, this is what I need. Thank you for keeping this website, I’ll be visiting it. Do you do newsletters? Cant find it.

  20. RWC Melbourne表示:

    Thanks for sharing superb informations. Your website is very cool. I am impressed by the details that you?ve on this web site. It reveals how nicely you perceive this subject. Bookmarked this website page, will come back for extra articles. You, my friend, ROCK! I found just the info I already searched all over the place and just couldn’t come across. What an ideal site.

  21. Throughout this awesome pattern of things you’ll get an A+ for effort. Where exactly you confused us was in your facts. As it is said, the devil is in the details… And that couldn’t be more correct here. Having said that, let me say to you precisely what did do the job. Your authoring is certainly incredibly powerful and that is most likely why I am making the effort in order to opine. I do not really make it a regular habit of doing that. 2nd, whilst I can see a jumps in reason you make, I am not really convinced of just how you seem to unite your points which inturn help to make the actual final result. For right now I will, no doubt subscribe to your point however wish in the future you actually link your facts much better.

  22. Hey there! I’ve been reading your web site for a long time now and finally got the bravery to go ahead and give you a shout out from Dallas Texas! Just wanted to say keep up the great work!

  23. Divirta-se no cassino mais confiavel Blaze

  24. Heya i am for the primary time here. I came across this board and I in finding It truly useful & it helped me out a lot. I’m hoping to provide something again and aid others like you helped me.

  25. Thanks for helping me to achieve new strategies about computer systems. I also have belief that one of the best ways to keep your laptop computer in leading condition has been a hard plastic material case, or perhaps shell, that matches over the top of one’s computer. These types of protective gear are generally model distinct since they are manufactured to fit perfectly on the natural casing. You can buy them directly from the owner, or through third party sources if they are for your laptop computer, however only a few laptop will have a cover on the market. Just as before, thanks for your tips.

  26. Thanks for your write-up. What I want to comment on is that while looking for a good on the internet electronics store, look for a website with comprehensive information on critical indicators such as the level of privacy statement, basic safety details, payment options, along with terms plus policies. Often take time to look at help plus FAQ pieces to get a much better idea of what sort of shop works, what they can do for you, and just how you can make use of the features.

  27. My brother recommended I might like this blog. He was entirely right. This post actually made my day. You can not imagine simply how much time I had spent for this information! Thanks!

  28. you could have an awesome blog here! would you like to make some invite posts on my weblog?

  29. One other thing I would like to say is that instead of trying to match all your online degree training on days and nights that you end work (considering that people are exhausted when they return), try to arrange most of your classes on the weekends and only 1 or 2 courses for weekdays, even if it means taking some time away from your weekend. This is fantastic because on the weekends, you will be far more rested in addition to concentrated with school work. Thx for the different suggestions I have discovered from your blog site.

  30. Cassinos com as melhores promocoes Blaze

發佈留言

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