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

  1. British put POWs to work for England: Many Axis prisoners of war at the moment are nearly actually Italians, as only a few Germans had been captured in 1940-1941.

  2. We’re a bunch of volunteers and opening a brand new scheme in our community. Your website provided us with helpful info to paintings on. You have performed a formidable task and our entire community will probably be thankful to you.

  3. Can you name the car shown here, which takes on both pony car and muscle car status?

  4. Opponents state that this legalizes cages until not less than 2022, and declare a few of the precise area laws (reminiscent of only permitting a single sq.

  5. Nowadays, smaller, more cost-effective systems are being developed for residential use, and large installations can place tanks almost anywhere, from buried underground to inside the building itself.

  6. Darrelherse表示:

    yeni slot siteleri: bonus veren casino slot siteleri – en cok kazandiran slot siteleri

  7. Bharat Petroleum (December 29, 2021).

  8. Appliances could be divided into separate rooms and entry to dwelling controls could be shared with others.

  9. Darrelherse表示:

    slot kumar siteleri: deneme bonusu veren siteler – slot bahis siteleri

  10. JesusLealt表示:

    deneme bonusu veren siteler: bonus veren siteler – bahis siteleri

  11. Products include, but are not limited to: futures on rainfall, snowfall, hurricanes, and temperature.

  12. However, after being shattered by massive artillery barrages and relentless infantry attacks, the city fell on May 9. Of the 230,000 Axis troops originally trapped on the peninsula, about 150,000 escaped by sea.

  13. Hi, Neat post. There’s a problem with your web site in internet explorer, would check this? IE still is the market leader and a big portion of people will miss your great writing because of this problem.

  14. Although Shih Tzus are non-aggressive, they’re rarely submissive.

  15. Hi would you mind stating which blog platform you’re working with? I’m looking to start my own blog in the near future but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique. P.S My apologies for getting off-topic but I had to ask!

  16. This is a national bestseller that provides secrets to building wealth in the stock market.

  17. Mazrzjz表示:

    Здравствуйте!
    Полезная информация как купить диплом о высшем образовании без рисков
    new.ogbpouvmk.ru/students/educational-resources

  18. Hello are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you require any coding knowledge to make your own blog? Any help would be really appreciated!

  19. Thanks on your marvelous posting! I seriously enjoyed reading it, you could be a great author.I will be sure to bookmark your blog and definitely will come back later on. I want to encourage you continue your great job, have a nice afternoon!

  20. As I web site possessor I believe the content material here is rattling wonderful , appreciate it for your hard work. You should keep it up forever! Good Luck.

  21. I have really noticed that credit repair activity needs to be conducted with tactics. If not, you will probably find yourself destroying your ranking. In order to be successful in fixing to your credit rating you have to take care that from this moment you pay all of your monthly costs promptly prior to their slated date. Really it is significant given that by definitely not accomplishing that area, all other methods that you will decide to use to improve your credit rating will not be helpful. Thanks for revealing your tips.

  22. Thank you for any other informative blog. Where else may I get that kind of information written in such a perfect means? I’ve a challenge that I am just now running on, and I’ve been on the glance out for such information.

  23. Hey There. I found your blog using msn. This is a really well written article. I?ll make sure to bookmark it and come back to read more of your useful info. Thanks for the post. I?ll certainly return.

  24. It made the data more useful.

  25. Zvsxdq表示:

    buy celebrex 100mg – buy celecoxib indocin 50mg for sale

  26. Thanks for these pointers. One thing I should also believe is that credit cards giving a 0 monthly interest often attract consumers with zero interest rate, instant acceptance and easy online balance transfers, nonetheless beware of the most recognized factor that will probably void your 0 easy neighborhood annual percentage rate as well as throw anybody out into the poor house rapidly.

  27. Magnificent beat ! I wish to apprentice at the same time as you amend your site, how can i subscribe for a blog site? The account aided me a appropriate deal. I have been tiny bit acquainted of this your broadcast provided vibrant clear concept

  28. I’ve really noticed that credit score improvement activity needs to be conducted with tactics. If not, it’s possible you’ll find yourself damaging your positioning. In order to succeed in fixing your credit ranking you have to see to it that from this time you pay any monthly fees promptly in advance of their slated date. It’s really significant for the reason that by not necessarily accomplishing so, all other measures that you will choose to use to improve your credit standing will not be powerful. Thanks for discussing your ideas.

  29. This is hands down one of the best articles I’ve read on this topic! The author’s extensive knowledge and zeal for the subject are apparent in every paragraph. I’m so grateful for coming across this piece as it has enhanced my understanding and sparked my curiosity even further. Thank you, author, for dedicating the time to create such a remarkable article!

  30. In April 2017, the government introduced a 334 sq.

發佈留言

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