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

11,310 Responses

  1. Helpful info. Fortunate me I discovered your web site by accident, and I am stunned why this accident didn’t took place in advance! I bookmarked it.

  2. Another issue is really that video gaming has become one of the all-time most significant forms of fun for people of all ages. Kids enjoy video games, and adults do, too. The particular XBox 360 is one of the favorite video games systems for those who love to have a lot of games available to them, and who like to experiment with live with some others all over the world. Thank you for sharing your ideas.

  3. I am curious to find out what blog system you happen to be using? I’m experiencing some small security problems with my latest site and I’d like to find something more risk-free. Do you have any recommendations?

  4. Sazrjvt表示:

    Добрый день!
    Диплом специалиста
    telegra.ph/kakoj-srednij-ball-attestata-dlya-postupleniya-v-vuz-08-02

  5. They should not be asked for different amounts of money to be a member of self managed super fund in Brisbane.

  6. Yrefilm表示:

    Здравствуйте!
    Купить диплом любого ВУЗа.
    fara-trading.com/impressive-health-benefits-of-saffron/#comment-44222

  7. Hello my friend! I wish to say that this post is awesome, nice written and include almost all significant infos. I?d like to see more posts like this.

  8. I relish, lead to I found just what I used to be taking a look for. You have ended my 4 day long hunt! God Bless you man. Have a great day. Bye

  9. For now, though, let’s look at the application Amazon has developed to deliver music from the Cloud Drive to your ears: the Amazon Cloud Player.

  10. Many investors do not accept this hypothesis, however, and believe that inefficiencies in the market persist and can be exploited.

  11. DouglasGed表示:

    Online medicine order: Online India pharmacy – india pharmacy

  12. One important issue is that while you are searching for a education loan you may find that you will need a co-signer. There are many scenarios where this is true because you should find that you do not have a past credit ranking so the mortgage lender will require that you’ve someone cosign the financial loan for you. Interesting post.

  13. Definitely believe that that you said. Your favorite reason seemed to be on the internet the easiest thing to consider of. I say to you, I definitely get annoyed even as other people consider worries that they just don’t recognise about. You controlled to hit the nail upon the highest as smartly as outlined out the entire thing with no need side effect , other folks could take a signal. Will likely be back to get more. Thank you

  14. DouglasGed表示:

    best india pharmacy: indian pharmacy – indian pharmacy online

  15. I love what you guys tend to be up too. This type of clever work and reporting! Keep up the superb works guys I’ve you guys to my personal blogroll.

  16. DouglasGed表示:

    indian pharmacies safe: Indian pharmacy international shipping – mail order pharmacy india

  17. cruella表示:

    F*ckin? remarkable things here. I?m very glad to see your post. Thanks a lot and i’m looking forward to contact you. Will you kindly drop me a mail?

  18. Its such as you learn my mind! You seem to grasp a lot approximately this, such as you wrote the guide in it or something. I think that you simply could do with some p.c. to pressure the message house a bit, but instead of that, that is great blog. An excellent read. I will definitely be back.

  19. Hurricane Michael made landfall as a Category 5 storm in 2018, causing an estimated $25.5 billion damage and 59 fatalities.

  20. The reason behind this phenomenon is that property is durable and its economic life is long enough.

  21. hunter killer表示:

    You actually 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!

  22. Right now it looks like WordPress is the best blogging platform out there right now. (from what I’ve read) Is that what you are using on your blog?

  23. Thanks for the tips you have provided here. Something important I would like to mention is that laptop or computer memory demands generally rise along with other advancements in the engineering. For instance, whenever new generations of processor chips are introduced to the market, there is usually a similar increase in the size preferences of both the personal computer memory and also hard drive room. This is because the software program operated by way of these processor chips will inevitably boost in power to make use of the new technological know-how.

  24. 項 どこ表示:

    As with so many other firsts, it was the Chinese who dreamed up the dandy idea of sweeping away doo-doo with good old paper.

  25. Diplomi_xqEa表示:

    Привет, друзья!
    Купить документ ВУЗа можно в нашей компании.
    cfgfactory.com/user/300528

  26. My partner and I absolutely love your blog and find nearly all of your post’s to be exactly I’m looking for. Do you offer guest writers to write content for you personally? I wouldn’t mind writing a post or elaborating on most of the subjects you write related to here. Again, awesome web site!

  27. Leonardpar表示:

    https://mexicopharmacy.win/# buying from online mexican pharmacy

  28. Leonardpar表示:

    https://mexicopharmacy.win/# buying prescription drugs in mexico

  29. alexa表示:

    One more thing is that while looking for a good on the internet electronics retail outlet, look for web stores that are frequently updated, maintaining up-to-date with the most up-to-date products, the most effective deals, along with helpful information on products and services. This will make sure that you are dealing with a shop which stays ahead of the competition and provides you things to make knowledgeable, well-informed electronics purchases. Thanks for the essential tips I’ve learned from the blog.

發佈留言

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