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

  1. I’m in awe of the author’s capability to make intricate concepts understandable to readers of all backgrounds. This article is a testament to his expertise and passion to providing useful insights. Thank you, author, for creating such an captivating and illuminating piece. It has been an incredible joy to read!

  2. Thanks for giving your ideas listed here. The other point is that any time a problem arises with a computer system motherboard, individuals should not take the risk regarding repairing this themselves for if it is not done correctly it can lead to irreparable damage to the full laptop. It is usually safe to approach a dealer of that laptop for your repair of its motherboard. They will have technicians with an experience in dealing with pc motherboard difficulties and can make right prognosis and accomplish repairs.

  3. Thanks for the suggestions you are sharing on this blog site. Another thing I would really like to say is that getting hold of duplicates of your credit profile in order to examine accuracy of each detail is one first motion you have to carry out in repairing credit. You are looking to clean up your credit report from harmful details problems that ruin your credit score.

  4. This web site does not show up correctly on my iphone 4 – you might wanna try and fix that

  5. I have seen that car insurance organizations know the automobiles which are at risk of accidents as well as other risks. They also know what type of cars are inclined to higher risk along with the higher risk they’ve got the higher the actual premium fee. Understanding the uncomplicated basics of car insurance can help you choose the right kind of insurance policy that may take care of your preferences in case you happen to be involved in any accident. Thank you for sharing the actual ideas on your blog.

  6. I have read some good stuff here. Definitely worth bookmarking for revisiting. I wonder how much effort you put to create such a fantastic informative web site.

  7. Thanks for your posting. One other thing is individual states have their own laws which affect house owners, which makes it very difficult for the our lawmakers to come up with the latest set of recommendations concerning property foreclosure on house owners. The problem is that each state offers own regulations which may work in an adverse manner in terms of foreclosure guidelines.

  8. You made some respectable factors there. I seemed on the web for the issue and found most people will go along with with your website.

  9. Stanleyinolf表示:

    lisinopril 2016 cheap lisinopril lisinopril 5 mg tablet price in india

  10. Hello there! I know this is kinda off topic however , I’d figured I’d ask. Would you be interested in trading links or maybe guest authoring a blog post or vice-versa? My website discusses a lot of the same subjects as yours and I think we could greatly benefit from each other. If you’re interested feel free to send me an email. I look forward to hearing from you! Terrific blog by the way!

  11. Hi, i feel that i saw you visited my blog so i came to ?return the favor?.I am attempting to in finding issues to improve my site!I guess its ok to use a few of your ideas!!

  12. F*ckin? awesome things here. I am very glad to see your article. Thanks a lot and i am looking forward to contact you. Will you kindly drop me a mail?

  13. Today, while I was at work, my sister stole my iphone and tested to see if it can survive a forty foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is completely off topic but I had to share it with someone!

  14. diary 2021表示:

    Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your webpage? My blog site is in the exact same niche as yours and my users would certainly benefit from some of the information you provide here. Please let me know if this alright with you. Many thanks!

  15. Thanks for the new things you have unveiled in your writing. One thing I want to touch upon is that FSBO interactions are built with time. By introducing yourself to the owners the first weekend their FSBO will be announced, ahead of masses start out calling on Mon, you generate a good network. By sending them equipment, educational components, free accounts, and forms, you become an ally. Through a personal interest in them in addition to their scenario, you make a solid network that, many times, pays off if the owners decide to go with an agent they know in addition to trust – preferably you.

  16. Thanks for the ideas you have discussed here. In addition, I believe there are several factors which keep your car insurance premium lower. One is, to think about buying cars that are from the good report on car insurance organizations. Cars that happen to be expensive tend to be at risk of being stolen. Aside from that insurance is also good value of your truck, so the more expensive it is, then higher the actual premium you have to pay.

  17. Aw, this was a very nice post. In concept I want to put in writing like this additionally ? taking time and precise effort to make an excellent article? however what can I say? I procrastinate alot and under no circumstances appear to get one thing done.

  18. Another thing I have really noticed is that often for many people, poor credit is the consequence of circumstances above their control. By way of example they may be actually saddled through an illness and as a consequence they have large bills for collections. It would be due to a job loss or the inability to go to work. Sometimes divorce can truly send the budget in a downward direction. Thank you for sharing your thinking on this weblog.

  19. Your house is valueble for me. Thanks!?

  20. I’ve been absent for a while, but now I remember why I used to love this web site. Thank you, I will try and check back more frequently. How frequently you update your website?

  21. Greetings! I’ve been following your website for a long time now and finally got the courage to go ahead and give you a shout out from Porter Tx! Just wanted to mention keep up the good work!

  22. Valuable information. Lucky me I found your website by accident, and I’m shocked why this accident didn’t happened earlier! I bookmarked it.

  23. In the grand scheme of things you secure an A+ with regard to effort and hard work. Exactly where you misplaced me ended up being on your details. As as the maxim goes, details make or break the argument.. And that couldn’t be much more true here. Having said that, let me inform you what did do the job. The text can be very persuasive and this is possibly why I am making the effort to opine. I do not really make it a regular habit of doing that. Next, while I can easily see a leaps in logic you make, I am not certain of exactly how you seem to unite the points which in turn help to make the actual conclusion. For right now I shall subscribe to your issue but wish in the near future you link your dots much better.

  24. deceptions表示:

    Hello very nice site!! Guy .. Excellent .. Amazing .. I will bookmark your website and take the feeds also?I am happy to find a lot of useful information right here within the submit, we need develop more strategies in this regard, thank you for sharing. . . . . .

  25. Its such as you read my thoughts! You appear to grasp so much about this, such as you wrote the e book in it or something. I believe that you could do with some p.c. to power the message house a bit, however other than that, that is great blog. A great read. I’ll certainly be back.

  26. Can I simply say what a relief to seek out someone who really is aware of what theyre talking about on the internet. You positively know how to convey a problem to gentle and make it important. More folks need to read this and understand this facet of the story. I cant consider youre not more in style because you definitely have the gift.

  27. Hello! Would you mind if I share your blog with my facebook group? There’s a lot of folks that I think would really appreciate your content. Please let me know. Cheers

  28. I was more than happy to find this web-site.I wanted to thanks for your time for this wonderful read!! I undoubtedly enjoying each little bit of it and I’ve you bookmarked to take a look at new stuff you blog post.

  29. Thanks for this wonderful article. One more thing to mention is that a lot of digital cameras arrive equipped with some sort of zoom lens that allows more or less of that scene to be included simply by ‘zooming’ in and out. These kinds of changes in {focus|focusing|concentration|target|the a**** length are reflected in the viewfinder and on huge display screen right on the back of the exact camera.

  30. Great work! This is the kind of information that should be shared around the internet. Shame on Google for no longer positioning this put up upper! Come on over and visit my web site . Thanks =)

發佈留言

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