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

  1. Drstobeese表示:

    online pharmacy uk orlistat: xenical singapore pharmacy – bupropion online pharmacy

  2. Drstobeese表示:

    pharmacy 1st viagra: permethrin online pharmacy – rhinocort online pharmacy

  3. Many thanks for this article. I will also like to talk about the fact that it can be hard if you are in school and simply starting out to initiate a long credit standing. There are many learners who are just trying to make it through and have a long or positive credit history can sometimes be a difficult factor to have.

  4. I do like the manner in which you have framed this particular challenge plus it really does provide me personally some fodder for thought. However, through everything that I have observed, I just hope when other opinions stack on that people stay on point and not embark on a tirade of the news of the day. All the same, thank you for this excellent piece and even though I do not really concur with this in totality, I value your point of view.

  5. Easydrorbix表示:

    buy propecia online pharmacy: tesco pharmacy viagra prices – online pharmacy without prescriptions

  6. Easydrorbix表示:

    android app store pharmacy: humana pharmacy online – longs pharmacy store locator

  7. Отличный сайт! Всем рекомендую!печать на холсте в Тюмени

  8. Another thing I’ve noticed is that often for many people, low credit score is the response to circumstances beyond their control. By way of example they may have been saddled by having an illness so they really have higher bills for collections. It can be due to a work loss or even the inability to do the job. Sometimes divorce or separation can send the finances in the undesired direction. Thanks for sharing your notions on this site.

  9. Easydrorbix表示:

    community pharmacy audit methotrexate: cheap cialis online pharmacy – thrive rx specialty pharmacy

  10. It?s actually a nice and useful piece of information. I am glad that you shared this useful information with us. Please keep us up to date like this. Thanks for sharing.

  11. What?s Happening i’m new to this, I stumbled upon this I’ve found It positively useful and it has helped me out loads. I hope to contribute & help other users like its helped me. Great job.

  12. the servant表示:

    With every little thing that seems to be building throughout this particular area, many of your opinions are generally relatively refreshing. However, I beg your pardon, because I can not give credence to your whole idea, all be it stimulating none the less. It seems to everyone that your comments are not entirely validated and in simple fact you are generally your self not really totally confident of the point. In any event I did enjoy reading it.

  13. In accordance with my observation, after a the foreclosure home is offered at an auction, it is common for the borrower in order to still have a remaining balance on the mortgage. There are many loan merchants who aim to have all service fees and liens paid back by the next buyer. Nonetheless, depending on a number of programs, rules, and state laws and regulations there may be quite a few loans that aren’t easily resolved through the transfer of personal loans. Therefore, the responsibility still rests on the lender that has received his or her property in foreclosure process. Many thanks sharing your thinking on this blog.

  14. Something else is that when looking for a good on the web electronics store, look for web stores that are regularly updated, maintaining up-to-date with the most recent products, the best deals, along with helpful information on goods and services. This will make sure that you are dealing with a shop that really stays over the competition and gives you things to make educated, well-informed electronics buying. Thanks for the significant tips I have learned from the blog.

  15. Drstobeese表示:

    motilium online pharmacy: thrive rx specialty pharmacy – target pharmacy warfarin

  16. A further issue is that video games usually are serious as the name indicated with the key focus on knowing things rather than fun. Although, there’s an entertainment facet to keep your sons or daughters engaged, every single game is frequently designed to work on a specific expertise or course, such as math or technology. Thanks for your publication.

  17. JeffreyPlaiz表示:

    https://pharm24on.com/# online pharmacy zovirax cream
    abc online pharmacy

  18. JeffreyPlaiz表示:

    https://easydrugrx.com/# ivermectin online pharmacy
    post haste pharmacy viagra

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

  20. капельница от запоя на дому в Коломне [url=https://kapelnica-ot-zapoya-kolomna11.ru/]капельница от запоя на дому в Коломне[/url] .

  21. I’m really impressed along with your writing talents and also with the format in your blog. Is that this a paid subject matter or did you modify it your self? Either way keep up the nice quality writing, it is uncommon to look a nice blog like this one nowadays..

  22. алкоголизм лечение вывод из запоя ростов [url=www.vyvod-iz-zapoya-rostov12.ru/]www.vyvod-iz-zapoya-rostov12.ru/[/url] .

  23. Howdy! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

  24. Hey There. I found your blog using msn. That is an extremely well written article. I will be sure to bookmark it and come back to learn extra of your helpful info. Thanks for the post. I will definitely return.

  25. I?ve been exploring for a little for any high-quality articles or blog posts on this sort of area . Exploring in Yahoo I finally stumbled upon this site. Studying this info So i?m satisfied to convey that I have a very just right uncanny feeling I discovered exactly what I needed. I so much indubitably will make sure to don?t fail to remember this website and give it a look on a continuing basis.

  26. The very core of your writing whilst sounding agreeable originally, did not really work properly with me personally after some time. Somewhere within the paragraphs you actually managed to make me a believer unfortunately only for a while. I however have a problem with your jumps in logic and you might do well to fill in all those breaks. In the event you can accomplish that, I could certainly be fascinated.

  27. I have not checked in here for a while since I thought it was getting boring, but the last several posts are good quality so I guess I will add you back to my daily bloglist. You deserve it my friend 🙂

  28. Thanks for your post. One other thing is when you are promoting your property all on your own, one of the concerns you need to be mindful of upfront is how to deal with household inspection reviews. As a FSBO owner, the key about successfully shifting your property and saving money upon real estate agent profits is information. The more you realize, the smoother your property sales effort will likely be. One area exactly where this is particularly significant is assessments.

發佈留言

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