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

16,077 Responses

  1. I have not checked in here for some time because I thought it was getting boring, but the last several posts are great quality so I guess I?ll add you back to my daily bloglist. You deserve it my friend 🙂

  2. Today, I went to the beach front 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 placed 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 totally off topic but I had to tell someone!

  3. One thing is always that one of the most widespread incentives for applying your cards is a cash-back and also rebate offer. Generally, you get 1-5 back for various expenses. Depending on the cards, you may get 1 back on most acquisitions, and 5 back on purchases made from convenience stores, gas stations, grocery stores as well as ‘member merchants’.

  4. Hey would you mind letting me know which web host you’re utilizing? I’ve loaded your blog in 3 different web browsers and I must say this blog loads a lot quicker then most. Can you recommend a good web hosting provider at a reasonable price? Kudos, I appreciate it!

  5. Howdy! I’m at work surfing around your blog from my new apple iphone! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the outstanding work!

  6. I was curious if you ever considered changing the page layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or two pictures. Maybe you could space it out better?

  7. I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on some general things, The web site style is perfect, the articles is really nice : D. Good job, cheers

  8. I have realized that in unwanted cameras, unique receptors help to {focus|concentrate|maintain focus|target|a**** automatically. These sensors involving some video cameras change in contrast, while others utilize a beam associated with infra-red (IR) light, specially in low light. Higher specification cameras sometimes use a combination of both programs and probably have Face Priority AF where the digicam can ‘See’ some sort of face while keeping focused only in that. Thank you for sharing your thinking on this web site.

  9. I believe that avoiding prepared foods is a first step to be able to lose weight. They can taste excellent, but prepared foods have very little vitamins and minerals, making you take in more to have enough vitality to get with the day. If you are constantly consuming these foods, switching to grain and other complex carbohydrates will aid you to have more vitality while having less. Good blog post.

  10. I can’t believe how amazing this article is! The author has done a tremendous job of presenting the information in an captivating and enlightening manner. I can’t thank her enough for providing such valuable insights that have certainly enriched my knowledge in this subject area. Bravo to him for creating such a masterpiece!

  11. I would also like to say that most individuals who find themselves devoid of health insurance are generally students, self-employed and people who are not working. More than half of the uninsured are under the age of 35. They do not feel they are looking for health insurance because they are young in addition to healthy. The income is often spent on homes, food, in addition to entertainment. Most people that do go to work either 100 or part-time are not made available insurance through their work so they proceed without owing to the rising tariff of health insurance in the states. Thanks for the suggestions you share through your blog.

  12. anime season表示:

    Generally I do not read article on blogs, but I would like to say that this write-up very forced me to try and do so! Your writing style has been amazed me. Thanks, quite nice post.

  13. Thanks for discussing your ideas. I’d also like to express that video games have been at any time evolving. Modern tools and revolutions have helped create genuine and active games. These entertainment video games were not that sensible when the actual concept was first being tried out. Just like other areas of technology, video games as well have had to evolve by way of many decades. This is testimony to the fast development of video games.

  14. One more thing. I do believe that there are lots of travel insurance websites of reputable companies that permit you to enter your vacation details to get you the estimates. You can also purchase the international holiday insurance policy online by using your credit card. All you should do would be to enter your travel details and you can see the plans side-by-side. Just find the system that suits your financial budget and needs then use your credit card to buy the item. Travel insurance on the web is a good way to begin looking for a dependable company pertaining to international travel cover. Thanks for revealing your ideas.

  15. What i do not realize is actually how you are not actually much more well-liked than you may be right now. You are so intelligent. You realize therefore considerably relating to this subject, produced me personally consider it from a lot of varied angles. Its like women and men aren’t fascinated unless it is one thing to do with Lady gaga! Your own stuffs excellent. Always maintain it up!

  16. Nearly all of whatever you mention is astonishingly precise and it makes me ponder why I had not looked at this with this light previously. This particular piece really did turn the light on for me as far as this specific subject goes. Nevertheless there is actually just one point I am not too comfy with and whilst I make an effort to reconcile that with the central idea of the point, allow me observe exactly what the rest of the visitors have to say.Well done.

  17. Hi, Neat post. There’s a problem with your website in web explorer, may test this? IE still is the market leader and a good section of people will leave out your great writing because of this problem.

  18. Nice blog here! Also your site loads up fast! What web host are you using? Can I get your affiliate link to your host? I wish my site loaded up as fast as yours lol

  19. in time 2020表示:

    Wow, incredible weblog layout! How long have you ever been blogging for? you make blogging glance easy. The whole look of your site is wonderful, let alone the content!

  20. Thanks for another fantastic post. Where else could anyone get that type of information in such an ideal way of writing? I have a presentation next week, and I’m on the look for such information.

  21. slice of life表示:

    You could definitely see your enthusiasm in the work you write. The world hopes for even more passionate writers like you who are not afraid to say how they believe. Always follow your heart.

  22. idx 70063138表示:

    This really answered my problem, thanks!

  23. This is hands down one of the greatest articles I’ve read on this topic! The author’s thorough knowledge and enthusiasm for the subject are apparent in every paragraph. I’m so grateful for coming across this piece as it has enhanced my comprehension and sparked my curiosity even further. Thank you, author, for taking the time to produce such a outstanding article!

  24. Howdy! Someone in my Facebook group shared this website with us so I came to take a look. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Great blog and excellent style and design.

  25. excellent post, very informative. I wonder why the other specialists of this sector do not notice this. You must continue your writing. I am confident, you’ve a huge readers’ base already!

  26. An added important area is that if you are a mature person, travel insurance pertaining to pensioners is something you ought to really take into consideration. The mature you are, the more at risk you’re for making something awful happen to you while overseas. If you are certainly not covered by a number of comprehensive insurance plan, you could have some serious problems. Thanks for revealing your good tips on this web blog.

  27. I have been exploring for a little for any high quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this web site. Reading this information So i am happy to convey that I’ve an incredibly good uncanny feeling I discovered exactly what I needed. I most certainly will make certain to don?t forget this website and give it a glance on a constant basis.

  28. Many thanks for your post. I’d prefer to comment that the price of car insurance varies widely from one scheme to another, for the reason that there are so many different facets which play a role in the overall cost. As an example, the make and model of the automobile will have a tremendous bearing on the charge. A reliable older family car or truck will have an inexpensive premium than just a flashy performance car.

發佈留言

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