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

  1. I don?t even know how I finished up right here, but I thought this publish was once great. I do not recognize who you are but certainly you’re going to a famous blogger should you aren’t already 😉 Cheers!

  2. Yreftjd表示:

    Привет, друзья!
    Купить диплом ВУЗа.
    gamecracks.ucoz.ru/index/25-851fd0ad7672baf8ba451463993a0d657d5505f6-1

  3. I like what you guys are up too. Such clever work and reporting! Keep up the superb works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my web site 🙂

  4. That is very interesting, You are a very professional blogger. I’ve joined your rss feed and sit up for searching for extra of your excellent post. Also, I have shared your website in my social networks!

  5. Have you ever thought about adding a little bit more than just your articles? I mean, what you say is valuable and everything. But think about if you added some great images or videos to give your posts more, “pop”! Your content is excellent but with pics and clips, this blog could certainly be one of the greatest in its field. Excellent blog!

  6. Hey There. I found your blog using msn. This is a really well written article. I will be sure to bookmark it and return to read more of your useful information. Thanks for the post. I will definitely return.

  7. Aw, this was a really nice post. In idea I want to put in writing like this moreover ? taking time and actual effort to make a very good article? however what can I say? I procrastinate alot and in no way seem to get one thing done.

  8. Hi there, simply was aware of your blog through Google, and located that it is truly informative. I?m gonna watch out for brussels. I?ll appreciate in the event you proceed this in future. Many people will likely be benefited out of your writing. Cheers!

  9. One thing is one of the most frequent incentives for applying your credit card is a cash-back and also rebate present. Generally, you will get 1-5 back upon various expenses. Depending on the card, you may get 1 again on most buying, and 5 back again on expenditures made from convenience stores, gasoline stations, grocery stores and ‘member merchants’.

  10. It is perfect time to make some plans for the future and it’s time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or tips. Perhaps you could write next articles referring to this article. I want to read even more things about it!

  11. One thing is that often one of the most popular incentives for using your cards is a cash-back as well as rebate present. Generally, you will get 1-5 back upon various acquisitions. Depending on the credit cards, you may get 1 again on most expenses, and 5 back again on buying made on convenience stores, filling stations, grocery stores as well as ‘member merchants’.

  12. One more thing. In my opinion that there are many travel insurance internet sites of respectable companies than enable you to enter a trip details and have you the estimates. You can also purchase the actual international travel insurance policy on the web by using your credit card. All you need to do is to enter your travel particulars and you can begin to see the plans side-by-side. Just find the package that suits your finances and needs then use your credit card to buy that. Travel insurance online is a good way to start looking for a respectable company for international holiday insurance. Thanks for giving your ideas.

  13. Howdy, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of spam comments? If so how do you stop it, any plugin or anything you can suggest? I get so much lately it’s driving me mad so any assistance is very much appreciated.

  14. Youre so cool! I dont suppose Ive read anything like this before. So good to seek out any person with some authentic thoughts on this subject. realy thanks for starting this up. this website is one thing that’s needed on the internet, somebody with a little originality. helpful job for bringing something new to the web!

  15. I have read several good stuff here. Certainly worth bookmarking for revisiting. I wonder how much effort you put to make such a excellent informative website.

  16. Hiya very nice site!! Guy .. Excellent .. Amazing .. I’ll bookmark your blog and take the feeds also?I’m glad to find numerous helpful info here in the publish, we’d like work out extra strategies in this regard, thanks for sharing. . . . . .

  17. Stephenzek表示:

    https://furosemide.win/# lasix 40mg

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

  19. This is hands down one of the finest articles I’ve read on this topic! The author’s comprehensive knowledge and enthusiasm for the subject shine through in every paragraph. I’m so grateful for stumbling upon this piece as it has deepened my comprehension and sparked my curiosity even further. Thank you, author, for dedicating the time to craft such a remarkable article!

  20. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your webpage? My blog site is in the very same area of interest as yours and my users would really benefit from some of the information you provide here. Please let me know if this okay with you. Appreciate it!

  21. Stephenzek表示:

    http://lisinopril.guru/# zestril 40

  22. perfecthalf2表示:

    Good write-up, I?m normal visitor of one?s blog, maintain up the nice operate, and It is going to be a regular visitor for a long time.

  23. I?ve been exploring for a little for any high-quality articles or weblog posts in this kind of house . Exploring in Yahoo I at last stumbled upon this web site. Studying this information So i?m satisfied to show that I have an incredibly excellent uncanny feeling I came upon just what I needed. I so much certainly will make certain to don?t overlook this web site and provides it a look on a continuing basis.

  24. I don?t even understand how I ended up here, but I believed this publish used to be great. I do not recognise who you might be however definitely you are going to a famous blogger if you happen to aren’t already 😉 Cheers!

  25. Thanks for your post. I would also love to say that a health insurance specialist also works well with the benefit of the actual coordinators of a group insurance policies. The health broker is given an index of benefits sought by an individual or a group coordinator. Exactly what a broker will is find individuals or maybe coordinators which will best complement those needs. Then he reveals his recommendations and if the two of you agree, the particular broker formulates legal contract between the two parties.

  26. Thanks for some other informative website. The place else may just I am getting that kind of information written in such a perfect way? I’ve a challenge that I am just now running on, and I have been at the look out for such information.

  27. Hello, Neat post. There is a problem with your site in internet explorer, would check this? IE nonetheless is the market leader and a huge component of folks will pass over your wonderful writing because of this problem.

  28. Definitely believe that which you said. Your favorite reason seemed to be on the internet the easiest thing to be aware of. I say to you, I definitely get annoyed while people think about worries that they plainly do not know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people could take a signal. Will likely be back to get more. Thanks

  29. Hello there, just was aware of your blog via Google, and located that it’s truly informative. I?m gonna be careful for brussels. I?ll appreciate should you continue this in future. Lots of people shall be benefited out of your writing. Cheers!

發佈留言

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