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

15,694 Responses

  1. I think one of your ads triggered my browser to resize, you may well want to put that on your blacklist.

  2. You really make it seem so easy with your presentation but I find this matter to be really something which I think I would never understand. It seems too complex and extremely broad for me. I’m looking forward for your next post, I?ll try to get the hang of it!

  3. It?s really a great and helpful piece of info. I am glad that you shared this helpful information with us. Please keep us informed like this. Thanks for sharing.

  4. Today, I went to the beach with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!

  5. I really believe that a foreclosed can have a significant effect on the borrower’s life. Mortgage foreclosures can have a 6 to several years negative impact on a borrower’s credit report. A new borrower who may have applied for a mortgage or any kind of loans for example, knows that the worse credit rating is usually, the more tricky it is to have a decent mortgage. In addition, it could possibly affect any borrower’s ability to find a quality place to let or hire, if that turns into the alternative homes solution. Interesting blog post.

  6. Thanks for your publication. I also think laptop computers have grown to be more and more popular today, and now are sometimes the only form of computer included in a household. The reason being at the same time that they are becoming more and more cost-effective, their working power is growing to the point where they can be as strong as desktop out of just a few in years past.

  7. Hiya, I am really glad I have found this info. Nowadays bloggers publish just about gossips and net and this is actually frustrating. A good website with exciting content, that is what I need. Thank you for keeping this site, I’ll be visiting it. Do you do newsletters? Can’t find it.

  8. Thanks for the tips you share through this website. In addition, many young women that become pregnant will not even seek to get medical care insurance because they have anxiety they would not qualify. Although many states currently require that insurers give coverage no matter the pre-existing conditions. Costs on these kind of guaranteed options are usually larger, but when thinking about the high cost of medical treatment it may be your safer strategy to use to protect a person’s financial potential.

  9. Thanks for the concepts you are revealing on this site. Another thing I would really like to say is the fact that getting hold of copies of your credit file in order to check accuracy of each detail could be the first motion you have to conduct in repairing credit. You are looking to cleanse your credit reports from dangerous details mistakes that mess up your credit score.

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

  11. Bangladesh Petroleum Company (February 13, 2023).

  12. This website online is mostly a stroll-by means of for the entire information you wanted about this and didn?t know who to ask. Glimpse right here, and also you?ll definitely discover it.

  13. Whats up! I just want to give an enormous thumbs up for the great info you have got right here on this post. I can be coming again to your weblog for more soon.

  14. Thanks for the suggestions about credit repair on this amazing web-site. The thing I would tell people is to give up this mentality that they can buy today and pay later. As being a society most people tend to try this for many issues. This includes family vacations, furniture, in addition to items we’d like. However, you have to separate your current wants out of the needs. As long as you’re working to fix your credit score you really have to make some trade-offs. For example it is possible to shop online to save cash or you can turn to second hand merchants instead of highly-priced department stores with regard to clothing.

  15. Thanks for the suggestions you have shared here. Something else I would like to express is that laptop memory needs generally increase along with other improvements in the technologies. For instance, as soon as new generations of processors are introduced to the market, there is usually a corresponding increase in the scale preferences of all laptop memory and also hard drive space. This is because the software program operated by these processor chips will inevitably rise in power to make use of the new technology.

  16. Thanks for your tips on this blog. 1 thing I would like to say is that often purchasing gadgets items over the Internet is not something new. In reality, in the past few years alone, the marketplace for online electronics has grown substantially. Today, you’ll find practically any type of electronic system and product on the Internet, including cameras and also camcorders to computer pieces and games consoles.

  17. I’m in awe of the author’s capability to make complex concepts accessible to readers of all backgrounds. This article is a testament to his expertise and dedication to providing valuable insights. Thank you, author, for creating such an captivating and enlightening piece. It has been an incredible joy to read!

  18. I beloved up to you will obtain performed right here. The sketch is tasteful, your authored subject matter stylish. however, you command get bought an impatience over that you wish be turning in the following. ill undoubtedly come further before again as exactly the same nearly a lot frequently inside case you shield this hike.

  19. One thing I’d like to touch upon is that fat reduction plan fast can be achieved by the appropriate diet and exercise. Ones size not simply affects the look, but also the quality of life. Self-esteem, depressive disorder, health risks, along with physical ability are impacted in excess weight. It is possible to just make everything right and still gain. If this happens, a problem may be the culprit. While a lot food instead of enough physical exercise are usually guilty, common health conditions and widely used prescriptions can easily greatly help to increase size. Thx for your post here.

  20. obviously like your web site however you have to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I to find it very troublesome to tell the reality then again I will surely come again again.

  21. Thanks for sharing these types of wonderful discussions. In addition, an excellent travel as well as medical insurance program can often eliminate those issues that come with touring abroad. The medical emergency can rapidly become too expensive and that’s absolute to quickly slam a financial impediment on the family’s finances. Setting up in place the ideal travel insurance package deal prior to setting off is well worth the time and effort. Thanks a lot

  22. I just like the helpful information you provide in your articles. I?ll bookmark your blog and check again here frequently. I am quite certain I will be told a lot of new stuff proper right here! Best of luck for the following!

  23. Thanks for giving your ideas right here. The other element is that each time a problem occurs with a computer motherboard, individuals should not consider the risk with repairing that themselves for if it is not done correctly it can lead to permanent damage to all the laptop. Most commonly it is safe to approach a dealer of the laptop for any repair of its motherboard. They will have technicians that have an know-how in dealing with pc motherboard challenges and can carry out the right prognosis and conduct repairs.

  24. After examine a few of the blog posts in your web site now, and I truly like your way of blogging. I bookmarked it to my bookmark web site listing and might be checking back soon. Pls try my web site as nicely and let me know what you think.

  25. 30 mph; an hour later, they had been 41 mph.

  26. Thanks for sharing these types of wonderful threads. In addition, an excellent travel as well as medical insurance approach can often relieve those worries that come with travelling abroad. A new medical emergency can quickly become too expensive and that’s bound to quickly impose a financial burden on the family finances. Putting in place the ideal travel insurance package prior to setting off is definitely worth the time and effort. Cheers

  27. I?d have to test with you here. Which is not one thing I often do! I enjoy studying a put up that can make folks think. Additionally, thanks for allowing me to remark!

  28. I have come across that these days, more and more people are attracted to surveillance cameras and the issue of picture taking. However, like a photographer, you need to first expend so much time deciding which model of dslr camera to buy in addition to moving store to store just so you could possibly buy the cheapest camera of the trademark you have decided to choose. But it doesn’t end now there. You also have to consider whether you should obtain a digital video camera extended warranty. Thx for the good points I gained from your web site.

  29. Normally I don’t learn post on blogs, however I would like to say that this write-up very pressured me to check out and do it! Your writing taste has been amazed me. Thank you, very great article.

  30. Thanks for the diverse tips discussed on this blog. I have observed that many insurance carriers offer clients generous special discounts if they opt to insure a few cars together. A significant quantity of households have got several cars these days, particularly people with more aged teenage young children still living at home, along with the savings with policies can easily soon increase. So it is good to look for a good deal.

發佈留言

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