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

  1. It’s appropriate time to make some plans for the long run and it is time to be happy. I’ve read this submit and if I could I desire to counsel you few interesting issues or advice. Perhaps you could write subsequent articles regarding this article. I wish to learn even more things about it!

  2. I just could not go away your website prior to suggesting that I really enjoyed the usual info an individual provide in your guests? Is gonna be again frequently in order to investigate cross-check new posts

  3. I just could not leave your website before suggesting that I extremely loved the usual information an individual supply to your guests? Is gonna be back steadily in order to check out new posts

  4. Turkey Tours表示:

    I appreciate your wp design, wherever would you download it through?

  5. Music started playing when I opened up this website, so frustrating!

  6. I am really impressed along with your writing skills and also with the format on your blog. Is that this a paid theme or did you customize it yourself? Either way keep up the nice high quality writing, it?s rare to look a nice blog like this one these days..

  7. TomasRop表示:

    farmacia online piГ№ conveniente: avanafil in farmacia – farmaci senza ricetta elenco

  8. Its like you learn my mind! You appear to know a lot approximately this, such as you wrote the book in it or something. I believe that you can do with some p.c. to pressure the message home a bit, however other than that, this is excellent blog. A great read. I will definitely be back.

  9. Hi, Neat post. There is a problem with your site in internet explorer, would test this? IE still is the market leader and a large portion of people will miss your wonderful writing because of this problem.

  10. RandyLunda表示:

    Farmacie on line spedizione gratuita: Farmacie che vendono Cialis senza ricetta – Farmacia online miglior prezzo

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

  12. TomasRop表示:

    farmacia online piГ№ conveniente: kamagra gold – acquistare farmaci senza ricetta

  13. RandyLunda表示:

    acquisto farmaci con ricetta: Avanafil 50 mg – farmacia online

  14. RandyLunda表示:

    alternativa al viagra senza ricetta in farmacia: acquisto viagra – viagra originale in 24 ore contrassegno

  15. 123hd tvpage3表示:

    I appreciate your wordpress design, where would you get a hold of it from?

  16. Lazruse表示:

    Привет!
    Мы изготавливаем дипломы психологов, юристов, экономистов и любых других профессий по доступным ценам.
    rushkadiplomiks.ru/kupit-diplom-krasnodar

  17. Amazing! This blog looks exactly like my old one! It’s on a entirely different topic but it has pretty much the same page layout and design. Superb choice of colors!

  18. Italy Tours表示:

    I feel this is among the such a lot important information for me. And i am happy studying your article. But should observation on some basic things, The site style is wonderful, the articles is really nice : D. Just right activity, cheers

  19. I like the valuable information you provide in your articles. I will bookmark your weblog and check again here regularly. I’m quite sure I will learn lots of new stuff right here! Best of luck for the next!

  20. Thanks for revealing your ideas. I might also like to express that video games have been actually evolving. Technology advances and inventions have made it easier to create authentic and enjoyable games. These kinds of entertainment games were not as sensible when the actual concept was being tried. Just like other kinds of technologies, video games way too have had to develop by means of many ages. This is testimony for the fast growth and development of video games.

  21. Fascinating blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple adjustements would really make my blog jump out. Please let me know where you got your design. Cheers

  22. Thanks for the diverse tips discussed on this blog. I have noticed that many insurance agencies offer customers generous reductions if they opt to insure multiple cars with them. A significant variety of households possess several automobiles these days, in particular those with elderly teenage young children still residing at home, and also the savings with policies might soon mount up. So it will pay to look for a bargain.

  23. TomasRop表示:

    viagra pfizer 25mg prezzo: viagra online – cialis farmacia senza ricetta

  24. I am really loving the theme/design of your weblog. Do you ever run into any browser compatibility problems? A number of my blog readers have complained about my website not working correctly in Explorer but looks great in Safari. Do you have any solutions to help fix this issue?

  25. Timothyzew表示:

    https://avanafil.pro/# top farmacia online

  26. Thanks for the suggestions you have shared here. Something important I would like to say is that laptop or computer memory requirements generally go up along with other advances in the technology. For instance, any time new generations of processor chips are made in the market, there is usually an equivalent increase in the dimensions calls for of all pc memory and also hard drive space. This is because the application operated by means of these processor chips will inevitably increase in power to use the new know-how.

  27. Thanks for sharing your ideas right here. The other thing is that whenever a problem takes place with a computer motherboard, people should not go ahead and take risk with repairing it themselves for if it is not done right it can lead to irreparable damage to the complete laptop. It is almost always safe just to approach any dealer of any laptop with the repair of its motherboard. They’ve got technicians that have an knowledge in dealing with mobile computer motherboard difficulties and can have the right diagnosis and perform repairs.

  28. Hi, Neat post. There’s a problem with your website in internet explorer, would check this? IE still is the market leader and a huge portion of people will miss your fantastic writing due to this problem.

  29. Thanks for the thoughts you discuss through this site. In addition, lots of young women who seem to become pregnant don’t even seek to get health care insurance because they dread they couldn’t qualify. Although some states now require that insurers produce coverage regardless of pre-existing conditions. Costs on these types of guaranteed programs are usually larger, but when taking into consideration the high cost of medical care bills it may be some sort of a safer way to go to protect your financial future.

  30. Thanks for discussing your ideas with this blog. In addition, a fable regarding the finance institutions intentions whenever talking about property foreclosures is that the financial institution will not getreceive my repayments. There is a certain amount of time the bank is going to take payments every now and then. If you are also deep inside hole, they will commonly desire that you pay the particular payment 100 . However, i am not saying that they will not take any sort of repayments at all. In the event you and the lender can seem to work one thing out, the foreclosure course of action may cease. However, in case you continue to pass up payments wih the new plan, the foreclosures process can just pick up exactly where it was left off.

發佈留言

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