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

27,744 Responses

  1. 789bet表示:

    Thanks for your thoughts. One thing I have noticed is banks plus financial institutions understand the spending routines of consumers and also understand that a lot of people max out their cards around the trips. They sensibly take advantage of this real fact and start flooding the inbox and also snail-mail box using hundreds of no-interest APR card offers soon after the holiday season comes to an end. Knowing that when you are like 98 of all American community, you’ll jump at the one opportunity to consolidate consumer credit card debt and shift balances to 0 apr interest rates credit cards.

  2. U888表示:

    Thanks for the recommendations you have contributed here. Yet another thing I would like to say is that laptop memory requirements generally increase along with other improvements in the technologies. For instance, if new generations of processor chips are made in the market, there’s usually an equivalent increase in the scale calls for of all laptop or computer memory and hard drive room. This is because the software program operated by way of these processors will inevitably increase in power to make new technologies.

  3. Hi88表示:

    Definitely believe that which you said. Your favorite reason seemed to be on the internet the simplest thing to be aware of. I say to you, I definitely get irked while people think about worries that they just don’t know about. You managed to hit the nail upon the top and also defined out the whole thing without having side effect , people can take a signal. Will likely be back to get more. Thanks

  4. Hi88表示:

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

  5. Hi88表示:

    You made some respectable factors there. I appeared on the web for the issue and located most people will go along with along with your website.

  6. WilsonVah表示:

    pharmacie en ligne france pas cher: kamagra oral jelly – pharmacie en ligne livraison europe

  7. Hi88表示:

    Hi! This is kind of off topic but I need some help from an established blog. Is it very difficult to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about setting up my own but I’m not sure where to start. Do you have any ideas or suggestions? Appreciate it

  8. WilsonVah表示:

    vente de mГ©dicament en ligne: kamagra livraison 24h – acheter mГ©dicament en ligne sans ordonnance

  9. Jacobbep表示:

    pharmacie en ligne sans ordonnance http://pharmaciemeilleurprix.com/# pharmacie en ligne livraison europe

  10. Hi88表示:

    I’m in awe of the author’s ability to make complex concepts understandable to readers of all backgrounds. This article is a testament to her expertise and dedication to providing useful insights. Thank you, author, for creating such an engaging and insightful piece. It has been an unforgettable experience to read!

  11. Jacobbep表示:

    pharmacie en ligne pas cher https://viagrameilleurprix.shop/# Prix du Viagra en pharmacie en France

  12. WW88表示:

    I have noticed that online degree is getting preferred because obtaining your college degree online has changed into a popular alternative for many people. Numerous people have definitely not had a possibility to attend a traditional college or university nevertheless seek the raised earning possibilities and career advancement that a Bachelors Degree affords. Still other folks might have a college degree in one field but would like to pursue a thing they now have an interest in.

  13. Richardprurf表示:

    https://pharmaciemeilleurprix.shop/# vente de mГ©dicament en ligne
    pharmacie en ligne

  14. WW88表示:

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

  15. WW88表示:

    Thanks for the new stuff you have unveiled in your short article. One thing I would like to reply to is that FSBO relationships are built after a while. By presenting yourself to the owners the first weekend their FSBO can be announced, prior to a masses begin calling on Thursday, you create a good link. By sending them equipment, educational elements, free records, and forms, you become a great ally. Through a personal curiosity about them and their circumstance, you develop a solid interconnection that, most of the time, pays off as soon as the owners opt with an agent they know plus trust – preferably you actually.

  16. Hi88表示:

    What i don’t understood is actually how you’re not really much more well-liked than you might be right now. You are so intelligent. You realize thus significantly relating to this subject, made me personally consider it from numerous varied angles. Its like women and men aren’t fascinated unless it is one thing to do with Lady gaga! Your own stuffs nice. Always maintain it up!

  17. In practice, when used as a practical forecasting tool it may be preferable to the standard T-model, because the specific accounting items used as input values are generally more robust (that is, less susceptible to variation due to differences in accounting methods), hence possibly easier to estimate.

  18. Hi88表示:

    Howdy! This post couldn’t be written any better! Reading this post reminds me of my good old room mate! He always kept talking about this. I will forward this write-up to him. Pretty sure he will have a good read. Thank you for sharing!

  19. Hi88表示:

    It?s arduous to seek out educated people on this topic, but you sound like you realize what you?re talking about! Thanks

  20. WilsonVah表示:

    pharmacie en ligne france livraison belgique: Acheter Cialis – pharmacie en ligne livraison europe

  21. NorbertKep表示:

    pharmacie en ligne fiable: kamagra gel – Pharmacie sans ordonnance

  22. Richardprurf表示:

    https://tadalafilmeilleurprix.shop/# pharmacie en ligne fiable
    Pharmacie sans ordonnance

  23. WW88表示:

    Thanks a bunch for sharing this with all people you really understand what you’re speaking approximately! Bookmarked. Kindly additionally talk over with my website =). We will have a link trade agreement among us!

  24. NorbertKep表示:

    pharmacie en ligne avec ordonnance: pharmacie en ligne sans ordonnance – pharmacies en ligne certifiГ©es

  25. WW88表示:

    This article is absolutely incredible! The author has done a phenomenal job of conveying the information in an compelling and enlightening manner. I can’t thank him enough for offering such valuable insights that have definitely enriched my knowledge in this subject area. Bravo to her for producing such a gem!

  26. Richardprurf表示:

    https://viagrameilleurprix.com/# Viagra pas cher paris
    Pharmacie sans ordonnance

  27. google SEO表示:

    A big thank you for your article.Thanks Again. Keep writing.

  28. U888表示:

    I have mastered some new points from your web site about pc’s. Another thing I’ve always believed is that computer systems have become an item that each house must have for most reasons. They offer convenient ways to organize the home, pay bills, shop, study, pay attention to music and also watch television shows. An innovative approach to complete these tasks is with a computer. These desktops are mobile, small, potent and mobile.

  29. Richardprurf表示:

    http://viagrameilleurprix.com/# Viagra pas cher inde
    vente de mГ©dicament en ligne

  30. U888表示:

    One other issue is that if you are in a circumstances where you do not have a cosigner then you may want to try to make use of all of your educational funding options. You could find many awards and other scholarship grants that will supply you with money that can help with classes expenses. Thanks a lot for the post.

發佈留言

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