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

  1. This actually answered my downside, thank you!

  2. Wonderful goods from you, man. I have understand your stuff previous to and you are just too magnificent. I actually like what you’ve acquired here, certainly like what you’re saying and the way in which you say it. You make it enjoyable and you still take care of to keep it wise. I can not wait to read much more from you. This is actually a wonderful website.

  3. Arnoldten表示:

    mexican rx online mexican pharmaceuticals online pharmacies in mexico that ship to usa

  4. Thanks for giving your ideas with this blog. Additionally, a delusion regarding the finance institutions intentions if talking about property foreclosures is that the financial institution will not have my payments. There is a degree of time that this bank will take payments in some places. If you are also deep inside the hole, they are going to commonly require that you pay the particular payment entirely. However, i am not saying that they will not take any sort of installments at all. Should you and the financial institution can have the ability to work a little something out, the actual foreclosure course of action may cease. However, if you continue to neglect payments in the new program, the property foreclosure process can pick up exactly where it left off.

  5. Valuable information. Lucky me I found your site by accident, and I am shocked why this accident didn’t happened earlier! I bookmarked it.

  6. Commercial mortgages wouldn’t allow that.

  7. Thanks for another wonderful article. Where else could anyone get that type of info in such a perfect method of writing? I have a presentation next week, and I am on the look for such info.

  8. You could definitely see your enthusiasm within the work you write. The sector hopes for more passionate writers like you who aren’t afraid to say how they believe. All the time follow your heart.

  9. Hey there! Someone in my Myspace group shared this site with us so I came to give it a look. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers! Terrific blog and excellent design.

  10. It’s the best time to make some plans for the future and it’s time to be happy. I have learn this post and if I could I wish to recommend you few attention-grabbing issues or suggestions. Perhaps you can write subsequent articles referring to this article. I desire to learn even more issues approximately it!

  11. Whats up! I just want to give an enormous thumbs up for the great information you will have right here on this post. I will be coming again to your blog for more soon.

  12. WayneCoirl表示:

    buying prescription drugs in mexico online: mexican drugstore online – mexico drug stores pharmacies

  13. One thing is the fact one of the most common incentives for utilizing your card is a cash-back or maybe rebate supply. Generally, you will get 1-5 back in various buying. Depending on the cards, you may get 1 returning on most expenses, and 5 back on buying made using convenience stores, gas stations, grocery stores plus ‘member merchants’.

  14. Hey! This is my first comment here so I just wanted to give a quick shout out and tell you I really enjoy reading your blog posts. Can you recommend any other blogs/websites/forums that go over the same topics? Thanks a lot!

  15. Sazrjsl表示:

    Привет, друзья!
    Диплом экономиста
    khvoynaya.getbb.ru/viewtopic.php?f=39&t=6874

  16. DominicJaw表示:

    mexico pharmacies prescription drugs: mexican rx online – reputable mexican pharmacies online

  17. Nelsonbluck表示:

    mexican pharmaceuticals online: medication from mexico pharmacy – mexican mail order pharmacies

  18. Great goods from you, man. I have understand your stuff previous to and you are just too wonderful. I actually like what you have acquired here, really like what you’re stating and the way in which you say it. You make it enjoyable and you still care for to keep it wise. I can’t wait to read far more from you. This is actually a tremendous web site.

  19. I was recommended this blog by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my difficulty. You are wonderful! Thanks!

  20. doofreeseries表示:

    excellent points altogether, you just gained a new reader. What would you suggest about your post that you made a few days ago? Any positive?

  21. We are a group of volunteers and starting a brand new scheme in our community. Your site provided us with helpful information to work on. You have performed a formidable job and our whole community shall be thankful to you.

  22. Yet another issue is that video gaming became one of the all-time largest forms of excitement for people of nearly every age. Kids participate in video games, and also adults do, too. The XBox 360 is amongst the favorite video games systems for many who love to have hundreds of activities available to them, and also who like to experiment with live with some others all over the world. Many thanks for sharing your notions.

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

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

  25. I’m truly enjoying the design and layout of your site. 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!

  26. Arnoldten表示:

    mexico pharmacy reputable mexican pharmacies online mexico drug stores pharmacies

  27. Thank you for the sensible critique. Me & my neighbor were just preparing to do a little research on this. We got a grab a book from our area library but I think I learned more clear from this post. I’m very glad to see such wonderful info being shared freely out there.

  28. There are some attention-grabbing points in time on this article but I don?t know if I see all of them middle to heart. There may be some validity however I’ll take hold opinion till I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as properly

  29. I think this is among the most important info for me. And i’m glad reading your article. But want to remark on few general things, The site style is ideal, the articles is really nice : D. Good job, cheers

  30. Good blog post. Some tips i would like to bring about is that computer memory must be purchased when your computer cannot cope with anything you do with it. One can install two good old ram boards of 1GB each, in particular, but not one of 1GB and one with 2GB. One should look for the company’s documentation for the PC to ensure what type of storage is needed.

發佈留言

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