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

  1. I’m not sure why but this weblog is loading incredibly slow for me. Is anyone else having this problem or is it a issue on my end? I’ll check back later on and see if the problem still exists.

  2. I have taken note that of all kinds of insurance, health insurance is the most questionable because of the conflict between the insurance coverage company’s necessity to remain profitable and the customer’s need to have insurance cover. Insurance companies’ revenue on overall health plans are certainly low, consequently some businesses struggle to make a profit. Thanks for the strategies you share through your blog.

  3. MichaelToP表示:

    farmacia online Cialis generico farmacia comprare farmaci online all’estero

  4. Edgarappow表示:

    farmacia online piГ№ conveniente: Cialis generico farmacia – comprare farmaci online all’estero

  5. I just couldn’t depart your web site prior to suggesting that I extremely loved the usual information an individual provide to your guests? Is gonna be again often to check out new posts

  6. Edgarappow表示:

    farmacie online autorizzate elenco: Cialis generico 5 mg prezzo – acquisto farmaci con ricetta

  7. Great website. Lots of useful information here. I?m sending it to some friends ans additionally sharing in delicious. And naturally, thanks in your sweat!

  8. Edgarappow表示:

    farmacia online senza ricetta: Brufen 600 senza ricetta – Farmacia online miglior prezzo

  9. Something more important is that while searching for a good on the web electronics store, look for web stores that are constantly updated, preserving up-to-date with the most recent products, the best deals, along with helpful information on goods and services. This will make certain you are handling a shop that really stays over the competition and offers you what you should need to make educated, well-informed electronics buys. Thanks for the critical tips I have really learned through your blog.

  10. Generally 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 amazed me. Thanks, quite nice post.

  11. Если вы искали где отремонтировать сломаную технику, обратите внимание – техпрофи

  12. Kennethtub表示:

    http://tadalafilit.com/# п»їFarmacia online migliore
    acquistare farmaci senza ricetta

  13. Thanks for your strategies. One thing I have noticed is that banks plus financial institutions understand the spending behavior of consumers and understand that many people max out and about their credit cards around the trips. They correctly take advantage of this fact and then start flooding ones inbox along with snail-mail box along with hundreds of no-interest APR card offers shortly when the holiday season finishes. Knowing that should you be like 98 of all American general public, you’ll hop at the chance to consolidate financial debt and switch balances to 0 interest rate credit cards.

  14. Kennethtub表示:

    http://farmaciait.men/# migliori farmacie online 2024
    migliori farmacie online 2024

  15. Thanks for your strategies. One thing I’ve got noticed is always that banks and financial institutions really know the spending behavior of consumers and as well understand that the majority of people max out their own credit cards around the breaks. They correctly take advantage of this kind of fact and begin flooding your own inbox plus snail-mail box together with hundreds of no interest APR credit card offers right after the holiday season concludes. Knowing that if you are like 98 of the American community, you’ll rush at the chance to consolidate credit card debt and shift balances to 0 apr interest rates credit cards.

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

  17. After research a few of the blog posts in your website now, and I really like your method of blogging. I bookmarked it to my bookmark web site checklist and will be checking back soon. Pls try my web page as nicely and let me know what you think.

  18. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:ремонт бытовой техники в ростове на дону
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  19. Pretty nice post. I just stumbled upon your blog and wished to say that I’ve truly enjoyed browsing your blog posts. In any case I will be subscribing to your feed and I hope you write again very soon!

  20. One more thing is that when looking for a good internet electronics shop, look for online shops that are consistently updated, retaining up-to-date with the hottest products, the most beneficial deals, and helpful information on services and products. This will ensure you are getting through a shop that really stays over the competition and give you what you ought to make intelligent, well-informed electronics buying. Thanks for the critical tips I have really learned from your blog.

  21. MichaelToP表示:

    Farmacia online miglior prezzo Cialis generico recensioni migliori farmacie online 2024

  22. I have noticed that smart real estate agents all around you are Advertising and marketing. They are realizing that it’s more than just placing a sign post in the front place. It’s really about building relationships with these retailers who at some time will become buyers. So, once you give your time and efforts to helping these traders go it alone — the “Law of Reciprocity” kicks in. Thanks for your blog post.

  23. Richardral表示:

    pillole per erezioni fortissime viagra generico sandoz viagra pfizer 25mg prezzo

  24. Richardral表示:

    farmacie online autorizzate elenco Brufen 600 senza ricetta farmacia online

  25. Kennethtub表示:

    http://sildenafilit.pro/# siti sicuri per comprare viagra online
    Farmacie on line spedizione gratuita

  26. Richardral表示:

    acquisto farmaci con ricetta Cialis generico farmacia comprare farmaci online all’estero

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

  28. Edgarappow表示:

    viagra ordine telefonico: acquisto viagra – viagra consegna in 24 ore pagamento alla consegna

  29. MichaelToP表示:

    farmacia online senza ricetta Cialis generico prezzo farmacie online sicure

  30. I will right away grab your rss as I can not to find your e-mail subscription link or e-newsletter service. Do you’ve any? Kindly allow me know so that I may subscribe. Thanks.

發佈留言

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