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

35,455 Responses

  1. RobertCex表示:

    oyun siteleri: casibom – canlД± casino bonusu veren siteler casibom1st.com

  2. whoah this blog is fantastic i love reading your articles. Keep up the great work! You know, many people are looking around for this information, you could aid them greatly.

  3. sex trẻ em表示:

    I think that a foreclosures can have a major effect on the client’s life. Real estate foreclosures can have a Several to few years negative affect on a applicant’s credit report. A borrower that has applied for home financing or almost any loans for example, knows that your worse credit rating can be, the more tricky it is to secure a decent loan. In addition, it could possibly affect a borrower’s capability to find a quality place to let or hire, if that results in being the alternative homes solution. Interesting blog post.

  4. Wonderful paintings! This is the type of info that are supposed to be shared around the net. Disgrace on the search engines for no longer positioning this submit higher! Come on over and consult with my web site . Thank you =)

  5. Davidled表示:

    https://casinositeleri1st.shop/# bonusu veren siteler

  6. I just added this weblog to my rss reader, excellent stuff. Cannot get enough!

  7. GarrettMom表示:

    lisansl? casino siteleri canlД± bahis siteleri deneme bonusu veren bet siteleri casinositeleri1st.shop

  8. This is undoubtedly one of the finest articles I’ve read on this topic! The author’s extensive knowledge and zeal for the subject are evident in every paragraph. I’m so thankful for coming across this piece as it has deepened my understanding and sparked my curiosity even further. Thank you, author, for dedicating the time to create such a phenomenal article!

  9. I believe that avoiding prepared foods may be the first step in order to lose weight. They will taste fine, but ready-made foods currently have very little nutritional value, making you take in more to have enough electricity to get over the day. When you are constantly eating these foods, converting to cereals and other complex carbohydrates will make you to have more vigor while feeding on less. Thanks alot : ) for your blog post.

  10. Hello! This is my first comment here so I just wanted to give a quick shout out and tell you I really enjoy reading through your posts. Can you recommend any other blogs/websites/forums that deal with the same subjects? Thanks a lot!

  11. RobertCex表示:

    bet gГјncel giriЕџ: casibom giris adresi – deneme bonusu veren seat casibom1st.com

  12. One more thing. I do believe that there are a lot of travel insurance web pages of reliable companies that allow you enter a trip details and have you the rates. You can also purchase the international holiday insurance policy on-line by using the credit card. Everything you should do should be to enter your current travel specifics and you can see the plans side-by-side. You only need to find the system that suits your capacity to pay and needs after which it use your credit card to buy the idea. Travel insurance online is a good way to take a look for a reliable company regarding international holiday insurance. Thanks for sharing your ideas.

  13. Davidled表示:

    http://sweetbonanza1st.com/# sweet bonanza giris

  14. BradyGem表示:

    siteler bahis: casibom giris – deneme bonusu veren seat casibom1st.com

  15. Hi! I’ve been reading your blog for some time now and finally got the courage to go ahead and give you a shout out from New Caney Tx! Just wanted to mention keep up the fantastic work!

  16. sex trẻ em表示:

    I would also love to add when you do not already have got an insurance policy or else you do not belong to any group insurance, you might well really benefit from seeking the help of a health insurance broker. Self-employed or individuals with medical conditions usually seek the help of the health insurance brokerage service. Thanks for your article.

  17. I believe one of your commercials triggered my internet browser to resize, you might want to put that on your blacklist.

  18. We are a bunch of volunteers and opening a brand new scheme in our community. Your site offered us with helpful info to work on. You have performed an impressive activity and our entire community will likely be thankful to you.

  19. It’s perfect time to make some plans for the future and it’s time to be happy. I’ve read this post and if I could I want to suggest you some interesting things or suggestions. Maybe you can write next articles referring to this article. I desire to read more things about it!

  20. You actually make it seem so easy with your presentation but I find this matter to be actually something which I think I would never understand. It seems too complex and very broad for me. I’m looking forward for your next post, I will try to get the hang of it!

  21. One thing I want to say is that often car insurance canceling is a terrifying experience and if you are doing the appropriate things being a driver you may not get one. Lots of people do receive the notice that they’ve been officially dropped by their own insurance company they then have to fight to get additional insurance after a cancellation. Low cost auto insurance rates are often hard to get from a cancellation. Understanding the main reasons with regard to auto insurance termination can help motorists prevent getting rid of in one of the most important privileges accessible. Thanks for the strategies shared via your blog.

  22. I would love to add that if you do not already have an insurance policy or else you do not form part of any group insurance, you will well take advantage of seeking the aid of a health insurance professional. Self-employed or those that have medical conditions commonly seek the help of one health insurance dealer. Thanks for your short article.

  23. BrianTom表示:

    medicine prednisone 10mg Pred Pharm Net prednisone 20mg nz

  24. Superb post however I was wanting to know if you could write a litte more on this topic? I’d be very grateful if you could elaborate a little bit further. Kudos!

  25. F*ckin? awesome issues here. I?m very satisfied to peer your post. Thanks a lot and i’m having a look ahead to contact you. Will you please drop me a mail?

  26. Its such as you read my mind! You seem to know a lot approximately this, like you wrote the ebook in it or something. I think that you could do with some p.c. to power the message home a bit, but other than that, that is fantastic blog. A great read. I will certainly be back.

  27. LanceFen表示:

    prednisone tablets: where to buy prednisone uk – where to get prednisone

  28. wonderful post, very informative. I wonder why the other experts of this sector don’t notice this. You should continue your writing. I am confident, you have a huge readers’ base already!

  29. Michaelscoob表示:

    how to buy clomid price: Clom Fast Pharm – Clom Fast Pharm

  30. Richardaudit表示:

    http://zithpharmonline.com/# ZithPharmOnline

發佈回覆給「sex trẻ em」的留言 取消回覆

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