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

19,869 Responses

  1. Hey there! Do you use Twitter? I’d like to follow you if that would be ok. I’m undoubtedly enjoying your blog and look forward to new posts.

  2. Whoa! This blog looks just like my old one! It’s on a entirely different topic but it has pretty much the same layout and design. Outstanding choice of colors!

  3. This is the precise weblog for anyone who wants to search out out about this topic. You notice a lot its virtually arduous to argue with you (not that I truly would need?HaHa). You definitely put a brand new spin on a topic thats been written about for years. Nice stuff, simply nice!

  4. A formidable share, I simply given this onto a colleague who was doing a little analysis on this. And he in actual fact bought me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If potential, as you develop into expertise, would you mind updating your weblog with more particulars? It’s extremely helpful for me. Massive thumb up for this blog post!

  5. This is very interesting, You’re a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your excellent post. Also, I’ve shared your site in my social networks!

  6. Thanks for every other magnificent post. Where else may just anybody get that kind of information in such an ideal manner of writing? I have a presentation subsequent week, and I’m at the look for such information.

  7. Lazrtvp表示:

    Привет, друзья!
    Мы готовы предложить дипломы любых профессий по приятным ценам.
    appleincub.ru/diplomyi-dlya-uverennyih-v-sebe-lyudey

  8. Thank you for another magnificent article. Where else could anybody get that type of information in such an ideal way of writing? I’ve a presentation next week, and I’m on the look for such info.

  9. Drstobeese表示:

    hq pharmacy online 365: online pharmacy jobs – tamiflu pharmacy

  10. Drstobeese表示:

    acyclovir pharmacy: animal rx pharmacy – isotretinoin prices pharmacy

  11. My brother suggested I would possibly like this blog. He used to be totally right. This post actually made my day. You cann’t believe simply how so much time I had spent for this information! Thank you!

  12. One other issue is when you are in a situation where you will not have a cosigner then you may genuinely wish to try to make use of all of your financing options. You will find many funds and other free college funding that will ensure that you get money to help you with institution expenses. Thanks for the post.

  13. Thanks for your helpful article. One other problem is that mesothelioma cancer is generally a result of the inhalation of materials from asbestos fiber, which is a very toxic material. Its commonly seen among staff in the engineering industry who have long experience of asbestos. It could be caused by moving into asbestos insulated buildings for an extended time of time, Genetic makeup plays a huge role, and some individuals are more vulnerable towards the risk compared to others.

  14. Thanks for the thoughts you are sharing on this blog site. Another thing I’d prefer to say is the fact getting hold of some copies of your credit file in order to check accuracy of any detail may be the first action you have to undertake in credit restoration. You are looking to clean your credit history from destructive details flaws that wreck your credit score.

  15. I appreciate, cause I found just what I was looking for. You’ve ended my 4 day long hunt! God Bless you man. Have a great day. Bye

  16. Excellent post however I was wanting to know if you could write a litte more on this topic? I’d be very grateful if you could elaborate a little bit further. Cheers!

  17. Interesting article. It is quite unfortunate that over the last 10 years, the travel industry has already been able to to tackle terrorism, SARS, tsunamis, flu virus, swine flu, as well as first ever entire global economic downturn. Through it all the industry has proven to be robust, resilient and also dynamic, obtaining new tips on how to deal with misfortune. There are often fresh challenges and chance to which the business must just as before adapt and react.

  18. Hello would you mind letting me know which hosting company you’re utilizing? I’ve loaded your blog in 3 completely different internet browsers and I must say this blog loads a lot quicker then most. Can you recommend a good web hosting provider at a reasonable price? Many thanks, I appreciate it!

  19. I feel that is one of the so much vital information for me. And i’m glad studying your article. However want to observation on some common things, The site style is perfect, the articles is actually great : D. Just right process, cheers

  20. Drstobeese表示:

    celebrex pharmacy prices: mexican pharmacy online medications – united pharmacy online

  21. Thanks for this excellent article. Also a thing is that most digital cameras come equipped with a new zoom lens that permits more or less of a scene to become included simply by ‘zooming’ in and out. These types of changes in {focus|focusing|concentration|target|the a**** length tend to be reflected in the viewfinder and on substantial display screen right on the back of the particular camera.

  22. Thank you for another informative site. Where else could I get that type of info written in such a perfect way? I have a project that I am just now working on, and I have been on the look out for such information.

  23. Music began playing any time I opened this web page, so irritating!

  24. Hi there, You have performed an excellent job. I?ll certainly digg it and for my part suggest to my friends. I’m confident they’ll be benefited from this site.

  25. Many thanks for sharing all these wonderful articles. In addition, the optimal travel and also medical insurance approach can often reduce those concerns that come with visiting abroad. A new medical crisis can shortly become costly and that’s sure to quickly impose a financial stress on the family finances. Putting in place the best travel insurance package deal prior to leaving is definitely worth the time and effort. Thanks

  26. Hey very cool blog!! Man .. Beautiful .. Amazing .. I’ll bookmark your website and take the feeds also?I’m happy to find so many useful information here in the post, we need work out more strategies in this regard, thanks for sharing. . . . . .

  27. Greetings from Ohio! I’m bored to death at work so I decided to browse your site on my iphone during lunch break. I enjoy the knowledge you provide here and can’t wait to take a look when I get home. I’m amazed at how quick your blog loaded on my mobile .. I’m not even using WIFI, just 3G .. Anyways, good site!

發佈留言

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