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

15,606 Responses

  1. Lazrsws表示:

    Здравствуйте!
    Мы можем предложить дипломы психологов, юристов, экономистов и прочих профессий по приятным ценам.
    ntsr.info/forum/user/98246

  2. Darrelherse表示:

    casino slot siteleri: oyun siteleri slot – slot siteleri guvenilir

  3. Darrelherse表示:

    yeni slot siteleri: en iyi slot siteleri 2024 – bonus veren casino slot siteleri

  4. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza slot

  5. I’ve been surfing on-line greater than three hours as of late, yet I by no means found any interesting article like yours. It is lovely value sufficient for me. In my opinion, if all webmasters and bloggers made excellent content material as you did, the internet can be a lot more useful than ever before.

  6. Another thing I’ve really noticed is always that for many people, low credit score is the reaction of circumstances outside of their control. By way of example they may have already been saddled with an illness and as a consequence they have more bills going to collections. It can be due to a occupation loss or perhaps the inability to work. Sometimes separation and divorce can truly send the money in the undesired direction. Thanks sharing your opinions on this web site.

  7. You actually make it appear so easy with your presentation but I to find this matter to be really one thing which I believe I would never understand. It sort of feels too complex and very broad for me. I am taking a look ahead in your next post, I will try to get the dangle of it!

  8. Darrelherse表示:

    bonus veren casino slot siteleri: slot kumar siteleri – en guvenilir slot siteleri

  9. жби изделия каталог http://kupit-zhbi.ru .

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

  11. KevinSounc表示:

    https://sweetbonanza.network/# sweet bonanza giris

  12. Thanks for sharing your ideas in this article. The other thing is that every time a problem comes up with a laptop or computer motherboard, folks should not have some risk associated with repairing it themselves for if it is not done right it can lead to permanent damage to all the laptop. Most commonly it is safe just to approach your dealer of any laptop for any repair of that motherboard. They’ve already technicians who may have an know-how in dealing with laptop motherboard challenges and can make right prognosis and conduct repairs.

  13. As I website possessor I believe the content matter here is rattling excellent , appreciate it for your hard work. You should keep it up forever! Best of luck.

  14. Hi, i read your blog from time to time and i own a similar one and i was just curious if you get a lot of spam responses? If so how do you protect against it, any plugin or anything you can suggest? I get so much lately it’s driving me crazy so any assistance is very much appreciated.

  15. I’m amazed by the quality of this content! The author has undoubtedly put a great amount of effort into researching and arranging the information. It’s exciting to come across an article that not only provides helpful information but also keeps the readers captivated from start to finish. Hats off to her for making such a remarkable piece!

  16. Thanks for your publication. What I want to point out is that when evaluating a good on the net electronics store, look for a internet site with comprehensive information on critical factors such as the personal privacy statement, protection details, payment options, and also other terms and also policies. Often take time to investigate the help in addition to FAQ pieces to get a greater idea of the way the shop works, what they are capable of doing for you, and in what way you can use the features.

  17. Thanks for giving your ideas right here. The other matter is that if a problem occurs with a pc motherboard, people should not consider the risk regarding repairing that themselves because if it is not done right it can lead to permanent damage to the whole laptop. It is almost always safe just to approach a dealer of your laptop for your repair of the motherboard. They’ve technicians that have an experience in dealing with mobile computer motherboard problems and can get the right analysis and accomplish repairs.

  18. Nice blog here! Also your web site loads up fast! What host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as fast as yours lol

  19. Aw, this was a very nice post. In concept I wish to put in writing like this additionally ? taking time and precise effort to make a very good article? but what can I say? I procrastinate alot and under no circumstances seem to get one thing done.

  20. Excellent goods from you, man. I have bear in mind your stuff previous to and you’re just too magnificent. I actually like what you’ve bought here, certainly like what you are stating and the way in which during which you say it. You make it enjoyable and you still care for to keep it wise. I cant wait to read far more from you. That is actually a tremendous site.

  21. Visit my web blog :: Daycares By Category (cthardwoodfloorcleaning.com)

  22. Another thing I’ve really noticed is that often for many people, low credit score is the results of circumstances beyond their control. Such as they may have been saddled by having an illness and because of this they have excessive bills for collections. It would be due to a job loss and the inability to go to work. Sometimes divorce process can really send the finances in the undesired direction. Thank you for sharing your ideas on this weblog.

  23. okmark your blog and check again here regularly. I am quite certain I will learn many new stuff right here! Good luck for the next!

  24. It’s a pity you don’t have a donate button! I’d certainly donate to this outstanding blog! I suppose for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to brand new updates and will share this site with my Facebook group. Chat soon!

  25. I do believe that a property foreclosures can have a significant effect on the applicant’s life. Home foreclosures can have a Several to few years negative effects on a borrower’s credit report. The borrower that has applied for home financing or any kind of loans even, knows that your worse credit rating is definitely, the more difficult it is to get a decent financial loan. In addition, it could affect a new borrower’s chance to find a respectable place to lease or rent, if that gets to be the alternative homes solution. Thanks for your blog post.

  26. The things i have seen in terms of computer memory is that there are requirements such as SDRAM, DDR or anything else, that must fit the specs of the mother board. If the pc’s motherboard is very current while there are no computer OS issues, upgrading the storage space literally normally requires under one hour. It’s one of several easiest laptop upgrade processes one can envision. Thanks for discussing your ideas.

發佈留言

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