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

  1. I appreciate, cause I found exactly what I was looking for. You have ended my 4 day long hunt! God Bless you man. Have a great day. Bye

  2. Thanks for enabling me to gain new ideas about computers. I also contain the belief that one of the best ways to help keep your laptop computer in leading condition has been a hard plastic-type case, and also shell, that matches over the top of your computer. A lot of these protective gear tend to be model unique since they are made to fit perfectly over the natural housing. You can buy these directly from the owner, or from third party sources if they are for your mobile computer, however only a few laptop can have a spend on the market. Again, thanks for your ideas.

  3. Does your site have a contact page? I’m having a tough time locating it but, I’d like to send you an e-mail. I’ve got some suggestions for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it develop over time.

  4. Thanks, I’ve been looking for info about this subject for ages and yours is the best I’ve discovered so far.

  5. I just added this blog site to my feed reader, great stuff. Can not get enough!

  6. We would also like to express that most individuals that find themselves with no health insurance usually are students, self-employed and those that are without a job. More than half in the uninsured are really under the age of Thirty five. They do not sense they are wanting health insurance because they’re young plus healthy. Its income is typically spent on real estate, food, in addition to entertainment. Some people that do work either complete or in their free time are not offered insurance via their jobs so they move without due to the rising tariff of health insurance in america. Thanks for the strategies you write about through this web site.

  7. I have read several good stuff here. Certainly value bookmarking for revisiting. I surprise how a lot attempt you place to make this sort of wonderful informative site.

  8. Wow! This could be one particular of the most beneficial blogs We have ever arrive across on this subject. Actually Wonderful. I’m also a specialist in this topic so I can understand your effort.

  9. vk namnoonmi表示:

    Please let me know if you’re looking for a author for your weblog. You have some really great posts and I think I would be a good asset. If you ever want to take some of the load off, I’d really like to write some material for your blog in exchange for a link back to mine. Please shoot me an e-mail if interested. Many thanks!

  10. I was wondering if you ever considered changing the layout of your website? 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?

  11. Thank you, I’ve been searching for information about this subject for ages and yours is the best I have located so far.

  12. I am curious to find out what blog platform you are using? I’m experiencing some small security problems with my latest site and I would like to find something more safe. Do you have any recommendations?

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

  14. After examine a couple of of the blog posts in your web site now, and I really like your method of blogging. I bookmarked it to my bookmark website list and might be checking again soon. Pls try my website online as well and let me know what you think.

  15. My partner and I stumbled over here coming from a different web address and thought I may as well check things out. I like what I see so i am just following you. Look forward to looking into your web page for a second time.

  16. you’re really a good webmaster. The web site loading speed is amazing. It seems that you are doing any unique trick. Moreover, The contents are masterwork. you’ve done a fantastic job on this topic!

  17. Oh my goodness! an incredible article dude. Thank you However I am experiencing situation with ur rss . Don?t know why Unable to subscribe to it. Is there anybody getting similar rss problem? Anyone who knows kindly respond. Thnkx

  18. Definitely believe that which you stated. Your favorite justification appeared 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 as well as defined out the whole thing without having side-effects , people can take a signal. Will probably be back to get more. Thanks

  19. I have learn a few good stuff here. Certainly value bookmarking for revisiting. I surprise how a lot effort you put to create one of these magnificent informative website.

  20. One thing I would like to say is that before obtaining more computer system memory, look at the machine in to which it would be installed. Should the machine is actually running Windows XP, for instance, the actual memory ceiling is 3.25GB. Installing over this would merely constitute any waste. Be sure that one’s mother board can handle an upgrade quantity, as well. Good blog post.

  21. Thanks for this excellent article. One other thing is that almost all digital cameras are available equipped with the zoom lens so that more or less of a scene to get included by simply ‘zooming’ in and out. These kinds of changes in {focus|focusing|concentration|target|the a**** length usually are reflected inside the viewfinder and on substantial display screen on the back of the exact camera.

  22. Hello! Someone in my Facebook group shared this website 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! Outstanding blog and superb design.

  23. What an eye-opening and well-researched article! The author’s thoroughness and aptitude to present complex ideas in a digestible manner is truly commendable. I’m extremely impressed by the scope of knowledge showcased in this piece. Thank you, author, for sharing your wisdom with us. This article has been a true revelation!

  24. Wow that was strange. I just wrote an extremely long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say wonderful blog!

  25. Hey there just wanted to give you a brief heads up and let you know a few of the images aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different web browsers and both show the same results.

  26. Thank you, I’ve just been looking for information about this topic for ages and yours is the best I’ve discovered so far. But, what about the bottom line? Are you sure about the source?

  27. Attractive portion of content. I just stumbled upon your blog and in accession capital to claim that I acquire in fact loved account your blog posts. Any way I?ll be subscribing for your augment or even I success you access constantly fast.

  28. We absolutely love your blog and find most of your post’s to be what precisely I’m looking for. Would you offer guest writers to write content for yourself? I wouldn’t mind composing a post or elaborating on some of the subjects you write about here. Again, awesome web site!

  29. вывод из запоя в стационаре ростов вывод из запоя в стационаре ростов .

發佈留言

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