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

  1. Attractive part of content. I just stumbled upon your blog and in accession capital to say that I acquire actually loved account your blog posts. Anyway I will be subscribing to your feeds and even I achievement you get right of entry to constantly rapidly.

  2. Thanks for the thoughts you share through this web site. In addition, numerous young women which become pregnant do not even aim to get medical health insurance because they fear they might not qualify. Although some states currently require that insurers produce coverage in spite of the pre-existing conditions. Rates on these guaranteed programs are usually bigger, but when considering the high cost of medical care it may be your safer way to go to protect your financial potential.

  3. Hey, I think your website might be having browser compatibility issues. When I look at your website in Chrome, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, very good blog!

  4. It?s actually a great and helpful piece of information. I am happy that you just shared this helpful information with us. Please keep us informed like this. Thanks for sharing.

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

  6. Hmm is anyone else encountering problems with the images on this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog. Any suggestions would be greatly appreciated.

  7. Hi I am so glad I found your webpage, I really found you by accident, while I was browsing on Digg for something else, Regardless I am here now and would just like to say cheers for a marvelous post and a all round enjoyable blog (I also love the theme/design), I don’t have time to browse it all at the minute but I have saved it and also added in your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the superb work.

  8. Thank you for another magnificent article. Where else could anybody get that kind of info in such an ideal means of writing? I’ve a presentation subsequent week, and I’m on the look for such info.

  9. Thanks for your information on this blog. Just one thing I want to say is that often purchasing electronics items on the Internet is certainly not new. The fact is, in the past few years alone, the marketplace for online electronic devices has grown noticeably. Today, you’ll find practically any type of electronic system and gizmo on the Internet, from cameras and camcorders to computer pieces and gaming consoles.

  10. Great write-up, I?m regular visitor of one?s website, maintain up the nice operate, and It is going to be a regular visitor for a lengthy time.

  11. bokep jilbab表示:

    Hello I am so excited I found your blog, I really found you by accident, while I was researching on Askjeeve for something else, Anyhow I am here now and would just like to say thanks for a remarkable post and a all round entertaining blog (I also love the theme/design), I don’t have time to read through it all at the minute but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the great work.

  12. Thanks for your posting on the vacation industry. I’d also like contribute that if you’re a senior contemplating traveling, it is absolutely essential that you buy traveling insurance for seniors. When traveling, elderly people are at high risk of having a medical emergency. Obtaining the right insurance plan package on your age group can look after your health and give you peace of mind.

  13. My brother suggested I might like this website. He was totally right. This post truly made my day. You cann’t imagine just how much time I had spent for this information! Thanks!

  14. pure cbd oil表示:

    One other issue is that if you are in a problem where you don’t have a co-signer then you may want to try to wear out all of your financing options. You can find many grants or loans and other free college funding that will supply you with money to assist with institution expenses. Thank you for the post.

  15. Hello this is somewhat of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding experience so I wanted to get guidance from someone with experience. Any help would be enormously appreciated!

  16. I?ll immediately grab your rss feed as I can’t find your email subscription link or newsletter service. Do you’ve any? Please let me know so that I could subscribe. Thanks.

  17. naturally like your web-site but you have to check the spelling on several of your posts. Many of them are rife with spelling problems and I find it very bothersome to tell the truth nevertheless I?ll definitely come back again.

  18. Thank you for the auspicious writeup. It if truth be told used to be a amusement account it. Look complicated to more introduced agreeable from you! However, how can we keep up a correspondence?

  19. Howdy! This is my first comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading through your blog posts. Can you recommend any other blogs/websites/forums that go over the same subjects? Appreciate it!

  20. One more thing. It’s my opinion that there are numerous travel insurance web pages of reliable companies that allow you enter your journey details and find you the rates. You can also purchase the particular international travel insurance policy on the net by using the credit card. Everything you need to do is always to enter the travel information and you can understand the plans side-by-side. Just find the plan that suits your finances and needs and after that use your bank credit card to buy the item. Travel insurance on the web is a good way to check for a respectable company with regard to international travel cover. Thanks for discussing your ideas.

  21. you are truly a excellent webmaster. The web site loading velocity is amazing. It sort of feels that you are doing any distinctive trick. Also, The contents are masterpiece. you’ve performed a wonderful process on this subject!

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

  23. Hello! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no data backup. Do you have any methods to prevent hackers?

  24. I was just looking for this info for a while. After six hours of continuous Googleing, at last I got it in your website. I wonder what’s the lack of Google strategy that do not rank this kind of informative web sites in top of the list. Normally the top web sites are full of garbage.

  25. In these days of austerity and relative panic about having debt, most people balk contrary to the idea of using a credit card in order to make purchase of merchandise or even pay for any occasion, preferring, instead only to rely on the tried plus trusted way of making transaction – hard cash. However, if you possess the cash there to make the purchase 100 , then, paradoxically, that is the best time to use the credit card for several factors.

  26. berc__bvKa表示:

    Откройте тайны берців зсу, Какую роль играют берці зсу в обрядах?, освойте, истории, тайны, сакральное значение, найдите, погрузитесь, культурой, Спробуйте на власній шкірі бути Берцем зсу, З чого починаються берці зсу, силу
    берці демісезонні зсу https://bercitaktichnizsu.vn.ua/ .

  27. Furthermore, i believe that mesothelioma cancer is a extraordinary form of many forms of cancer that is typically found in these previously subjected to asbestos. Cancerous tissues form within the mesothelium, which is a protecting lining which covers many of the body’s areas. These cells normally form in the lining in the lungs, belly, or the sac that really encircles the heart. Thanks for expressing your ideas.

  28. Its like you learn my mind! You appear to know so much approximately this, like you wrote the e book in it or something. I think that you just can do with a few to power the message home a little bit, however other than that, that is excellent blog. A great read. I will certainly be back.

  29. I do not even know how I stopped up right here, but I believed this put up was once great. I do not recognise who you’re but certainly you are going to a famous blogger in case you are not already 😉 Cheers!

  30. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You clearly know what youre talking about, why waste your intelligence on just posting videos to your site when you could be giving us something informative to read?

發佈留言

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