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

  1. I am sure this paragraph has touched all the internet visitors,
    its really really fastidious article on building
    up new webpage.

  2. I’ve read some good stuff here. Certainly value bookmarking for
    revisiting. I wonder how so much attempt you place to make this type of fantastic informative website.

  3. Brain表示:

    Touche. Outstanding arguments. Keep up the great work.

  4. My partner and I stumbled over here coming from a different web page and thought I should check things out.

    I like what I see so now i am following you. Look forward to exploring
    your web page repeatedly.

  5. fake bags表示:

    The other day, while I was at work, my cousin stole my apple ipad and tested to see if it can survive a 25 foot drop,
    just so she can be a youtube sensation. My apple
    ipad is now broken and she has 83 views. I know this is totally off topic but I had to
    share it with someone!

  6. Отличный сайт! Всем рекомендую! Тут Вы можете найтиброкер для скальпинга

  7. OLaneevige表示:

    Simply desire to say your article is as amazing. The clearness for your submit is simply excellent and i can suppose you are a professional on this subject. Well with your permission allow me to snatch your feed to keep up to date with drawing close post. Thank you 1,000,000 and please carry on the enjoyable work.
    @@G@@
    https://telephongid.ru/obshhie-voprosy/ip-telefoniya-sovremennye-uslugi-svyazi.html

  8. Cassino que voce vai adorar Blaze

  9. Jogue em um cassino confiavel Tigrinho

  10. Отличный сайт! Всем рекомендую! Тут Вы можете найтиброкеры для скальпинга

  11. Zwnpep表示:

    buy dulcolax 5mg online – cheap oxybutynin 2.5mg order liv52 10mg online

  12. A melhor escolha para jogos de azar Tigrinho

  13. Cassino on-line confiavel Tigrinho

  14. Tente a sorte no melhor cassino Tigrinho

  15. Thanks for the ideas you are discussing on this blog site. Another thing I’d really like to say is the fact that getting hold of duplicates of your credit profile in order to look at accuracy of the detail may be the first measures you have to undertake in repairing credit. You are looking to cleanse your credit file from dangerous details faults that wreck your credit score.

  16. Icsrxk表示:

    aciphex uk – reglan medication buy domperidone without a prescription

  17. One other issue is that if you are in a predicament where you would not have a co-signer then you may really want to try to exhaust all of your financing options. You can find many grants and other scholarships and grants that will give you funding to aid with school expenses. Many thanks for the post.

  18. I think one of your ads triggered my browser to resize, you might want to put that on your blacklist.

  19. Thanks for the ideas you have discussed here. Furthermore, I believe usually there are some factors that really keep your car insurance premium straight down. One is, to bear in mind buying motors that are inside good directory of car insurance businesses. Cars that are expensive are usually more at risk of being robbed. Aside from that insurance is also in line with the value of your automobile, so the higher priced it is, then higher the premium you spend.

  20. I truly appreciate this post. I?ve been looking everywhere for this! Thank goodness I found it on Bing. You have made my day! Thanks again

  21. I’m really enjoying the design and layout of your website. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a designer to create your theme? Fantastic work!

  22. Melhor cassino online Tigrinho

  23. O lugar perfeito para jogos de azar Tigrinho

  24. genius wave表示:

    You could definitely see your expertise in the work you write. The world hopes for even more passionate writers like you who are not afraid to say how they believe. Always follow your heart.

  25. Thank you, I have recently been searching for info about this topic for ages and yours is the best I’ve discovered so far. But, what about the conclusion? Are you sure about the source?

  26. Usually I don’t read post on blogs, but I wish to say that this write-up very forced me to try and do so! Your writing style has been surprised me. Thanks, quite nice article.

  27. Greetings from Los angeles! I’m bored to death at work so I decided to browse your blog on my iphone during lunch break. I enjoy 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 .. Anyways, amazing site!

  28. I found your blog site on google and check a number of of your early posts. Continue to keep up the very good operate. I simply additional up your RSS feed to my MSN News Reader. Searching for ahead to reading more from you afterward!?

  29. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You clearly know what youre talking about, why throw away your intelligence on just posting videos to your blog when you could be giving us something informative to read?

發佈留言

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