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

10,392 Responses

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

  2. Do you have a spam problem on this website; I also am a blogger, and I was wondering your situation; we have developed some nice procedures and we are looking to trade techniques with others, please shoot me an email if interested.

  3. superace777表示:

    It is really a nice and helpful piece of information. I am glad that you shared this helpful information with us. Please keep us informed like this. Thanks for sharing.

  4. lago777.me表示:

    I do not even know how I ended up here, but I thought this post was good. I do not know who you are but certainly you’re going to a famous blogger if you aren’t already 😉 Cheers!

  5. This actually answered my problem, thanks!

  6. super ace777表示:

    Hi there! I know this is kind of off topic but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one? Thanks a lot!

  7. Thanks for sharing your ideas with this blog. Likewise, a delusion regarding the banking institutions intentions when talking about foreclosed is that the lender will not have my repayments. There is a degree of time that this bank requires payments here and there. If you are very deep inside hole, they are going to commonly demand that you pay the payment 100 . However, i am not saying that they will not take any sort of installments at all. In the event you and the standard bank can have the ability to work something out, your foreclosure process may end. However, should you continue to miss out on payments beneath new approach, the foreclosed process can pick up where it was left off.

  8. superace777表示:

    This actually answered my problem, thank you!

  9. I am really enjoying the theme/design of your web site. Do you ever run into any browser compatibility problems? A couple of my blog readers have complained about my website not working correctly in Explorer but looks great in Firefox. Do you have any suggestions to help fix this problem?

  10. En guvenilir online casino Sweet bonanza

  11. I am curious to find out what blog system you are working with? I’m experiencing some minor security issues with my latest website and I would like to find something more safeguarded. Do you have any recommendations?

  12. En populer kumarhaneyi deneyin Sweet bonanza

  13. Rwpfee表示:

    purchase minoxidil online – finpecia order online order propecia online

  14. lago777 com表示:

    A powerful share, I simply given this onto a colleague who was doing a little evaluation on this. And he actually bought me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the deal with! However yeah Thnkx for spending the time to debate this, I feel strongly about it and love studying more on this topic. If doable, as you turn out to be experience, would you thoughts updating your weblog with more particulars? It’s extremely helpful for me. Massive thumb up for this weblog put up!

  15. 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 entirely off topic but I had to tell someone!

  16. lago777 login表示:

    What I have often told people today is that while searching for a good on the net electronics retail store, there are a few elements that you have to remember to consider. First and foremost, you want to make sure to choose a reputable plus reliable retailer that has enjoyed great opinions and rankings from other people and marketplace advisors. This will ensure that you are getting along with a well-known store to provide good services and support to it’s patrons. Many thanks for sharing your ideas on this site.

  17. Generally I don’t read article on blogs, but I wish to say that this write-up very forced me to try and do so! Your writing style has been surprised me. Thanks, quite nice post.

  18. Lien.N表示:

    Very interesting info!Perfect just what I was looking for!Raise blog range

  19. Wonderful site. Plenty of helpful information here. I am sending it to a few buddies ans also sharing in delicious. And obviously, thank you in your effort!

  20. lago777表示:

    Thanks for your post on the vacation industry. I would also like to add that if you are a senior taking into account traveling, its absolutely crucial that you buy traveling insurance for elderly people. When traveling, seniors are at greatest risk of getting a professional medical emergency. Buying the right insurance coverage package in your age group can look after your health and give you peace of mind.

  21. Thank you for any other informative website. Where else could I am getting that type of information written in such an ideal approach? I’ve a project that I’m simply now running on, and I have been on the look out for such information.

  22. There are some fascinating time limits on this article however I don?t know if I see all of them center to heart. There’s some validity however I will take maintain opinion till I look into it further. Good article , thanks and we want more! Added to FeedBurner as properly

  23. lago777 app表示:

    Thanks for the a new challenge you have discovered in your text. One thing I’d like to discuss is that FSBO interactions are built eventually. By bringing out yourself to owners the first saturday and sunday their FSBO is announced, prior to the masses start off calling on Wednesday, you create a good network. By sending them resources, educational materials, free reviews, and forms, you become a strong ally. If you take a personal desire for them along with their situation, you make a solid connection that, on most occasions, pays off once the owners opt with a real estate agent they know and also trust – preferably you actually.

  24. supperace777表示:

    This is really attention-grabbing, You’re an overly skilled blogger. I’ve joined your rss feed and look ahead to in search of more of your great post. Additionally, I’ve shared your website in my social networks!

  25. I have read several good stuff here. Certainly worth bookmarking for revisiting. I wonder how much effort you put to create such a excellent informative web site.

  26. My spouse and I stumbled over here from a different web address and thought I may as well check things out. I like what I see so now i’m following you. Look forward to looking at your web page again.

  27. I do not even know how I ended up here, but I thought this post was great. I don’t know who you are but certainly you’re going to a famous blogger if you aren’t already 😉 Cheers!

  28. Almost all of the things you claim happens to be astonishingly appropriate and that makes me wonder why I hadn’t looked at this with this light before. This particular article really did turn the light on for me as far as this particular topic goes. Nonetheless at this time there is actually one factor I am not necessarily too cozy with and while I make an effort to reconcile that with the core idea of the position, allow me see exactly what the rest of your visitors have to point out.Nicely done.

  29. Hey are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you need any coding knowledge to make your own blog? Any help would be really appreciated!

發佈留言

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