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

  1. PatrickTig表示:

    http://zithromaxbestprice.pro/# zithromax online usa

  2. Matthewchact表示:

    п»їcytotec pills online: buy cytotec pills – buy cytotec online fast delivery

  3. It?s arduous to find knowledgeable individuals on this matter, however you sound like you already know what you?re speaking about! Thanks

  4. Thanks for your posting. I would also love to say that the very first thing you will need to conduct is determine if you really need credit restoration. To do that you will need to get your hands on a replica of your credit rating. That should never be difficult, considering that the government mandates that you are allowed to have one free of charge copy of your credit report per year. You just have to check with the right individuals. You can either look into the website with the Federal Trade Commission and also contact one of the main credit agencies directly.

  5. RobertSic表示:

    prednisone 20 tablet buy prednisone nz canada buy prednisone online

  6. Diplomi_yjEa表示:

    Добрый день!
    Приобрести документ о получении высшего образования можно в нашем сервисе.
    asxdiplomik24.ru/kupit-diplom-s-registraciej

  7. These days of austerity and relative stress and anxiety about running into debt, lots of people balk against the idea of using a credit card to make acquisition of merchandise or even pay for a holiday, preferring, instead just to rely on the actual tried along with trusted procedure for making settlement – cash. However, if you’ve got the cash there to make the purchase completely, then, paradoxically, that’s the best time just to be able to use the credit cards for several motives.

  8. RobertHaumn表示:

    tamoxifen breast cancer: what is tamoxifen used for – nolvadex vs clomid

  9. Thanks for your concepts. One thing we’ve noticed is always that banks and financial institutions understand the spending patterns of consumers as well as understand that many people max outside their own credit cards around the getaways. They sensibly take advantage of this real fact and commence flooding your inbox and also snail-mail box by using hundreds of 0 APR card offers shortly after the holiday season closes. Knowing that if you are like 98 in the American open public, you’ll hop at the possiblity to consolidate credit card debt and move balances for 0 annual percentage rates credit cards.

  10. This site can be a stroll-through for the entire info you wanted about this and didn?t know who to ask. Glimpse here, and you?ll positively uncover it.

  11. LewisTwera表示:

    https://propeciabestprice.pro/# cost of propecia for sale

  12. PatrickTig表示:

    http://propeciabestprice.pro/# get cheap propecia pill

  13. Matthewchact表示:

    prednisone pharmacy: prednisone 30 mg coupon – 1 mg prednisone cost

  14. RobertSic表示:

    zithromax 1000 mg pills zithromax 500mg over the counter cost of generic zithromax

  15. Unquestionably believe that which you said. Your favourite justification seemed to be at the web the easiest factor to bear in mind of. I say to you, I definitely get irked at the same time as folks think about concerns that they plainly don’t recognize about. You controlled to hit the nail upon the top and also outlined out the whole thing without having side-effects , folks could take a signal. Will probably be back to get more. Thank you

  16. This design is spectacular! You most certainly know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Fantastic job. I really loved what you had to say, and more than that, how you presented it. Too cool!

  17. Pretty section of content. I just stumbled upon your website and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I will be subscribing to your augment and even I achievement you access consistently quickly.

  18. Hi my family member! I wish to say that this article is awesome, nice written and come with approximately all significant infos. I?d like to see more posts like this .

  19. jb_diary表示:

    We’re a gaggle of volunteers and starting a new scheme in our community. Your site provided us with helpful information to paintings on. You have performed an impressive job and our entire group can be thankful to you.

  20. littlecatzzz表示:

    I am really impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you modify it yourself? Either way keep up the nice quality writing, it is rare to see a nice blog like this one today..

  21. Hey there, You have done a fantastic job. I will definitely digg it and personally recommend to my friends. I’m sure they’ll be benefited from this site.

  22. Someone necessarily lend a hand to make severely posts I might state. This is the first time I frequented your website page and up to now? I surprised with the research you made to make this particular publish extraordinary. Wonderful process!

  23. I’m really enjoying the theme/design of your blog. Do you ever run into any browser compatibility issues? A couple of my blog audience have complained about my site not operating correctly in Explorer but looks great in Opera. Do you have any ideas to help fix this problem?

  24. Hey very cool web site!! Guy .. Excellent .. Amazing .. I will bookmark your blog and take the feeds also?I’m satisfied to seek out so many helpful info right here in the submit, we want work out more techniques on this regard, thank you for sharing. . . . . .

  25. I’m very happy to read this. This is the kind of manual that needs to be given and not the random misinformation that is at the other blogs. Appreciate your sharing this greatest doc.

  26. Hey there I am so excited I found your webpage, I really found you by mistake, while I was browsing on Google for something else, Regardless I am here now and would just like to say thanks a lot for a incredible post and a all round enjoyable blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have book-marked it and also added in your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the awesome work.

  27. Thanks for your posting. One other thing is the fact that individual states in the United states of america have their own laws in which affect home owners, which makes it quite difficult for the our elected representatives to come up with the latest set of rules concerning property foreclosures on property owners. The problem is that each state has got own legislation which may have impact in an undesirable manner in terms of foreclosure policies.

  28. khunpmhee表示:

    Coming from my examination, shopping for consumer electronics online can for sure be expensive, however there are some tips that you can use to help you get the best things. There are continually ways to come across discount offers that could make one to come across the best electronic devices products at the cheapest prices. Thanks for your blog post.

  29. Thank you for the good writeup. It actually used to be a entertainment account it. Glance complicated to far introduced agreeable from you! By the way, how can we communicate?

發佈留言

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