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

  1. Hello there, just changed into aware of your blog via Google, and located that it’s truly informative. I?m gonna watch out for brussels. I will be grateful when you proceed this in future. Lots of people will probably be benefited from your writing. Cheers!

  2. Hi there, I found your site via Google while looking for a related topic, your web site came up, it looks good. I’ve bookmarked it in my google bookmarks.

  3. Thanks for your write-up. One other thing is always that individual states have their particular laws which affect people, which makes it very difficult for the our elected representatives to come up with a new set of recommendations concerning property foreclosures on home owners. The problem is that each state provides own laws which may have impact in an adverse manner with regards to foreclosure insurance plans.

  4. JesusLealt表示:

    bahis siteleri: deneme bonusu – bahis siteleri

  5. It’s a pity you don’t have a donate button! I’d most certainly donate to this superb blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to new updates and will share this site with my Facebook group. Talk soon!

  6. Heya i?m for the first time here. I found this board and I to find It truly helpful & it helped me out a lot. I am hoping to offer one thing again and aid others like you helped me.

  7. Undeniably imagine that that you stated. Your favorite reason appeared to be at the net the easiest thing to have in mind of. I say to you, I certainly get irked even as other folks consider concerns that they just do not recognize about. You managed to hit the nail upon the highest as smartly as outlined out the entire thing with no need side-effects , other people could take a signal. Will likely be again to get more. Thank you

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

  9. Today, I went to the beachfront with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!

  10. amiispink tw表示:

    I have taken note that of all kinds of insurance, health insurance is the most questionable because of the conflict between the insurance company’s obligation to remain profitable and the client’s need to have insurance. Insurance companies’ commission rates on health plans are very low, thus some firms struggle to profit. Thanks for the ideas you talk about through this website.

  11. What i don’t realize is actually how you are not really much more well-liked than you might be right now. You’re so intelligent. You realize therefore significantly relating to this subject, made me personally consider it from numerous varied angles. Its like women and men aren’t fascinated unless it is one thing to accomplish with Lady gaga! Your own stuffs outstanding. Always maintain it up!

  12. Have you ever thought about adding a little bit more than just your articles? I mean, what you say is important and everything. Nevertheless think of if you added some great images or video clips to give your posts more, “pop”! Your content is excellent but with images and videos, this website could undeniably be one of the greatest in its field. Amazing blog!

  13. This site is known as a stroll-through for all the data you needed about this and didn?t know who to ask. Glimpse here, and you?ll positively uncover it.

  14. One thing I’d like to say is the fact that before obtaining more computer system memory, take a look at the machine within which it can be installed. In the event the machine is actually running Windows XP, for instance, the particular memory threshold is 3.25GB. The installation of more than this would easily constitute any waste. Make certain that one’s motherboard can handle the actual upgrade amount, as well. Great blog post.

  15. Undeniably believe that which you said. Your favorite justification seemed to be on the internet the easiest thing to be aware of. I say to you, I definitely get irked while people consider worries that they plainly don’t know about. You managed to hit the nail upon the top and also defined out the whole thing without having side effect , people could take a signal. Will probably be back to get more. Thanks

  16. Hi there! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no back up. Do you have any solutions to stop hackers?

  17. It is indeed my belief that mesothelioma is usually the most dangerous cancer. It contains unusual properties. The more I look at it the greater I am confident it does not conduct itself like a real solid cells cancer. If perhaps mesothelioma is a rogue viral infection, in that case there is the chance of developing a vaccine and offering vaccination to asbestos uncovered people who are at high risk involving developing future asbestos connected malignancies. Thanks for discussing your ideas about this important health issue.

  18. F*ckin? amazing issues here. I am very glad to peer your article. Thanks a lot and i’m having a look forward to touch you. Will you kindly drop me a mail?

  19. Hi there, You’ve performed a fantastic job. I will definitely digg it and in my opinion recommend to my friends. I’m confident they’ll be benefited from this web site.

  20. Good day! This post couldn’t be written any better! Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Fairly certain he will have a good read. Thanks for sharing!

  21. I have taken notice that in digital camera models, specialized sensors help to {focus|concentrate|maintain focus|target|a**** automatically. Those kind of sensors with some digital cameras change in contrast, while others use a beam of infra-red (IR) light, specifically in low lighting. Higher specs cameras at times use a combination of both techniques and may have Face Priority AF where the video camera can ‘See’ your face and focus only on that. Thank you for sharing your thinking on this website.

  22. Hello! I’ve been following your site for a while now and finally got the courage to go ahead and give you a shout out from Atascocita Tx! Just wanted to tell you keep up the great work!

  23. I just couldn’t depart your web site prior to suggesting that I extremely enjoyed the standard information a person provide for your visitors? Is going to be back often to check up on new posts

  24. It?s actually a nice and helpful piece of info. I am satisfied that you shared this helpful information with us. Please keep us informed like this. Thank you for sharing.

  25. Wonderful beat ! I would like to apprentice while you amend your site, how could i subscribe for a blog web site? The account aided me a acceptable deal. I had been tiny bit acquainted of this your broadcast offered bright clear idea

  26. whoah this blog is great i love reading your posts. Keep up the good work! You know, lots of people are searching around for this info, you could aid them greatly.

  27. I’ve been surfing online more than three hours today, yet I never found any interesting article like yours. It?s pretty worth enough for me. In my opinion, if all website owners and bloggers made good content as you did, the web will be much more useful than ever before.

  28. Mazrpyt表示:

    Добрый день!
    Как оказалось, купить диплом кандидата наук не так уж и сложно
    bizkerrefutboltaldea.com/bizkerre/Castellano/principal.htm

  29. Darrelherse表示:

    slot kumar siteleri: bonus veren casino slot siteleri – 2024 en iyi slot siteleri

發佈留言

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