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

  1. Greetings from Idaho! I’m bored to tears at work so I decided to check out your blog on my iphone during lunch break. I really like the information you present here and can’t wait to take a look when I get home. I’m surprised at how fast your blog loaded on my mobile .. I’m not even using WIFI, just 3G .. Anyhow, wonderful site!

  2. Throughout this awesome scheme of things you receive a B- with regard to hard work. Where exactly you actually confused me was in all the details. As as the maxim goes, details make or break the argument.. And it couldn’t be much more true here. Having said that, allow me inform you precisely what did do the job. The authoring is certainly pretty powerful which is probably why I am taking the effort in order to opine. I do not make it a regular habit of doing that. Next, while I can easily see the jumps in reason you come up with, I am not really certain of exactly how you appear to unite the ideas which make your final result. For the moment I will, no doubt subscribe to your point but hope in the foreseeable future you actually connect the facts much better.

  3. Unquestionably believe that which you said. Your favorite reason appeared to be on the net the simplest thing to be aware of. I say to you, I definitely get annoyed while people think about worries that they plainly don’t know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks

  4. I can’t express how much I appreciate the effort the author has put into producing this outstanding piece of content. The clarity of the writing, the depth of analysis, and the abundance of information provided are simply impressive. His passion for the subject is obvious, and it has undoubtedly struck a chord with me. Thank you, author, for providing your insights and enlightening our lives with this extraordinary article!

  5. Thanks a bunch for sharing this with all folks you actually realize what you’re speaking about! Bookmarked. Please additionally seek advice from my web site =). We can have a link trade agreement between us!

  6. Virtually all of the things you point out happens to be supprisingly precise and it makes me ponder the reason why I had not looked at this in this light previously. This piece truly did turn the light on for me as far as this topic goes. Nonetheless there is actually one factor I am not really too comfortable with so while I attempt to reconcile that with the actual main theme of your point, allow me observe what the rest of the visitors have to point out.Nicely done.

  7. Thanks for your publication. I also believe laptop computers are becoming more and more popular today, and now are often the only type of computer employed in a household. It is because at the same time potentially they are becoming more and more cost-effective, their processing power is growing to the point where there’re as powerful as desktop coming from just a few years back.

  8. Fantastic goods from you, man. I have be mindful your stuff prior to and you are just too magnificent. I actually like what you’ve received here, certainly like what you are saying and the way through which you are saying it. You are making it enjoyable and you continue to take care of to keep it wise. I cant wait to read much more from you. This is actually a terrific web site.

  9. I do not even know the way I finished up right here, but I thought this publish was once great. I do not understand who you might be however definitely you are going to a well-known blogger for those who are not already 😉 Cheers!

  10. Darrelherse表示:

    oyun siteleri slot: yeni slot siteleri – deneme bonusu veren siteler

  11. Thanks for these pointers. One thing I also believe is always that credit cards featuring a 0 interest rate often entice consumers in with zero rate, instant acceptance and easy over-the-internet balance transfers, however beware of the main factor that will void the 0 easy street annual percentage rate as well as throw one out into the bad house rapid.

  12. Thanks for the advice on credit repair on this particular site. Some tips i would offer as advice to people would be to give up a mentality that they may buy now and shell out later. As being a society most of us tend to do that for many factors. This includes holidays, furniture, in addition to items we’d like. However, you’ll want to separate your wants from all the needs. When you are working to improve your credit score make some sacrifices. For example you’ll be able to shop online to save cash or you can go to second hand suppliers instead of costly department stores regarding clothing.

  13. Thank you for the good writeup. It in reality was once a amusement account it. Look complex to more introduced agreeable from you! However, how can we be in contact?

  14. Undeniably consider that that you said. Your favorite reason seemed to be on the net the simplest thing to understand of. I say to you, I certainly get irked at the same time as folks consider concerns that they just do not recognise about. You managed to hit the nail upon the top and defined out the entire thing without having side-effects , other folks could take a signal. Will probably be back to get more. Thanks

  15. After I initially commented I clicked the -Notify me when new feedback are added- checkbox and now every time a comment is added I get 4 emails with the same comment. Is there any method you can take away me from that service? Thanks!

  16. I can’t express how much I appreciate the effort the author has put into creating this remarkable piece of content. The clarity of the writing, the depth of analysis, and the wealth of information offered are simply remarkable. Her passion for the subject is obvious, and it has undoubtedly made an impact with me. Thank you, author, for offering your knowledge and enriching our lives with this extraordinary article!

  17. Along with every little thing which seems to be developing throughout this specific subject material, a significant percentage of viewpoints are generally relatively stimulating. On the other hand, I beg your pardon, because I do not subscribe to your entire idea, all be it refreshing none the less. It seems to everybody that your remarks are generally not entirely validated and in fact you are generally yourself not really totally certain of your argument. In any case I did appreciate reading through it.

  18. I discovered your weblog website on google and check just a few of your early posts. Proceed to maintain up the superb operate. I just additional up your RSS feed to my MSN Information Reader. Seeking ahead to studying extra from you afterward!?

  19. Attractive section of content. I just stumbled upon your website and in accession capital to assert that I acquire actually enjoyed account your blog posts. Anyway I?ll be subscribing to your augment and even I achievement you access consistently quickly.

  20. You made some decent points there. I seemed on the web for the difficulty and found most people will associate with along with your website.

  21. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four e-mails with the same comment. Is there any way you can remove people from that service? Thanks!

  22. Hello, you used to write magnificent, but the last several posts have been kinda boring? I miss your super writings. Past few posts are just a bit out of track! come on!

  23. I don?t even know how I ended up here, but I thought this post was good. I do not know who you are but definitely you’re going to a famous blogger if you aren’t already 😉 Cheers!

  24. Good day! This is kind of off topic but I need some advice from an established blog. Is it hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about making my own but I’m not sure where to start. Do you have any ideas or suggestions? Thanks

  25. My spouse and I absolutely love your blog and find nearly all of your post’s to be what precisely I’m looking for. can you offer guest writers to write content to suit your needs? I wouldn’t mind creating a post or elaborating on a lot of the subjects you write concerning here. Again, awesome blog!

  26. As I website possessor I believe the content material here is rattling fantastic , appreciate it for your efforts. You should keep it up forever! Good Luck.

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

  28. Thanks for some other magnificent article. Where else may just anyone get that kind of info in such an ideal means of writing? I have a presentation subsequent week, and I am on the look for such information.

  29. I?m now not positive where you are getting your information, however good topic. I needs to spend a while finding out much more or working out more. Thank you for magnificent info I was in search of this information for my mission.

  30. Great work! This is the type of information that are supposed to be shared across the web. Shame on Google for not positioning this publish upper! Come on over and seek advice from my web site . Thanks =)

發佈留言

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