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

  1. Allenacurf表示:

    pharmacie en ligne avec ordonnance: kamagra livraison 24h – pharmacie en ligne france livraison belgique

  2. Allenacurf表示:

    Achat mГ©dicament en ligne fiable: cialis generique – pharmacie en ligne sans ordonnance

  3. Have you ever thought about adding a little bit more than just your articles? I mean, what you say is important and everything. However just imagine if you added some great photos or video clips to give your posts more, “pop”! Your content is excellent but with images and clips, this site could certainly be one of the very best in its field. Terrific blog!

  4. XRumer23obliz表示:

    Hello!

    This post was created with XRumer 23 StrongAI.

    Good luck 🙂

  5. Thanks for your post. I have usually seen that a majority of people are wanting to lose weight because they wish to show up slim as well as attractive. Nonetheless, they do not constantly realize that there are other benefits to losing weight as well. Doctors claim that fat people experience a variety of conditions that can be directly attributed to their excess weight. The good news is that people who sadly are overweight in addition to suffering from numerous diseases can help to eliminate the severity of their particular illnesses by way of losing weight. You’ll be able to see a progressive but marked improvement in health as soon as even a bit of a amount of weight loss is achieved.

  6. RobertBlica表示:

    http://phenligne.com/# pharmacie en ligne avec ordonnance

  7. Thanks a bunch for sharing this with all of us you really know what you’re talking about! Bookmarked. Kindly also visit my site =). We could have a link exchange agreement between us!

  8. Jogue em um cassino confiavel Fortune Tiger

  9. Ganhos maximos neste cassino Fortune Tiger

  10. Os melhores bonus deste cassino Fortune Tiger

  11. Jogue em um cassino confiavel Fortune Tiger

  12. Um cassino com uma excelente reputacao Fortune Tiger

  13. Allenacurf表示:

    Acheter viagra en ligne livraison 24h: Acheter du Viagra sans ordonnance – Viagra gГ©nГ©rique sans ordonnance en pharmacie

  14. EdwardGROOM表示:

    п»їpharmacie en ligne france: levitra en ligne – pharmacie en ligne france livraison belgique

  15. KeithKef表示:

    Pharmacie sans ordonnance kamagra oral jelly pharmacie en ligne

  16. taurus zodiac表示:

    I loved up to you’ll receive carried out proper here. The comic strip is attractive, your authored subject matter stylish. nonetheless, you command get got an nervousness over that you would like be handing over the following. in poor health without a doubt come more previously once more as precisely the same nearly very steadily inside case you shield this hike.

  17. EdwardGROOM表示:

    SildГ©nafil 100 mg sans ordonnance: Viagra Pfizer sans ordonnance – Viagra sans ordonnance livraison 24h

  18. EdwardGROOM表示:

    pharmacie en ligne france pas cher: Achat mГ©dicament en ligne fiable – Pharmacie sans ordonnance

  19. Allenacurf表示:

    Pharmacie sans ordonnance: Pharmacies en ligne certifiees – pharmacie en ligne france fiable

  20. One thing I’d like to comment on is that weight loss program fast can be achieved by the right diet and exercise. Your size not merely affects appearance, but also the overall quality of life. Self-esteem, depression, health risks, along with physical ability are afflicted in weight gain. It is possible to do everything right and still gain. In such a circumstance, a problem may be the reason. While a lot food and never enough body exercise are usually the culprit, common medical conditions and widely used prescriptions could greatly help to increase size. I am grateful for your post here.

  21. taurus gx4表示:

    I’m not that much of a online reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your website to come back down the road. Cheers

  22. Undeniably believe that which you said. Your favorite reason seemed to be on the web the easiest thing to be aware of. I say to you, I definitely get annoyed while people consider worries that they plainly do not know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side-effects , people could take a signal. Will probably be back to get more. Thanks

  23. Allenacurf表示:

    Viagra sans ordonnance 24h: Viagra generique en pharmacie – Viagra pas cher paris

  24. you may have a terrific blog here! would you like to make some invite posts on my weblog?

  25. Hello my friend! I want to say that this article is awesome, nice written and include almost all significant infos. I would like to see more posts like this.

  26. taurus 9mm表示:

    F*ckin? amazing issues here. I?m very glad to see your article. Thanks so much and i am taking a look forward to contact you. Will you kindly drop me a mail?

  27. I’m really enjoying the theme/design of your site. Do you ever run into any web browser compatibility problems? A number of my blog readers have complained about my site not operating correctly in Explorer but looks great in Safari. Do you have any solutions to help fix this problem?

  28. taurus 9mm表示:

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

  29. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You definitely know what youre talking about, why throw away your intelligence on just posting videos to your weblog when you could be giving us something enlightening to read?

發佈留言

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