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

  1. Experimente o cassino mais popular Blaze

  2. Hi my friend! I want to say that this article is awesome, nice written and include approximately all vital infos. I would like to see more posts like this.

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

  4. Do you mind if I quote a few of your posts as long as I provide credit and sources back to your webpage? My blog site is in the exact same area of interest as yours and my visitors would certainly benefit from some of the information you present here. Please let me know if this okay with you. Cheers!

  5. Your home is valueble for me. Thanks!?

  6. Oh my goodness! I’m in awe of the author’s writing skills and capability to convey intricate concepts in a concise and concise manner. This article is a real treasure that merits all the praise it can get. Thank you so much, author, for sharing your wisdom and providing us with such a priceless resource. I’m truly thankful!

  7. fake bags表示:

    For newest information you have to visit world-wide-web and
    on the web I found this website as a most excellent website for most recent updates.

  8. Thank you for any other informative blog. The place else may I am getting that kind of info written in such an ideal manner? I’ve a venture that I’m simply now running on, and I have been on the glance out for such information.

  9. Melhor cassino para jogos Blaze

  10. hey there and thank you for your info ? I have definitely picked up anything new from right here. I did however expertise a few technical issues using this website, since I experienced to reload the site lots of times previous to I could get it to load correctly. I had been wondering if your hosting is OK? Not that I’m complaining, but slow loading instances times will often affect your placement in google and can damage your high-quality score if ads and marketing with Adwords. Well I am adding this RSS to my e-mail and can look out for a lot more of your respective interesting content. Make sure you update this again soon..

  11. Melhores jogos neste cassino Blaze

  12. review表示:

    Heya i am for the first time here. I found this board and I find It really useful & it helped me out a lot. I hope to give something back and help others like you helped me.

  13. Gertie表示:

    Having read this I thought it was extremely enlightening.
    I appreciate you finding the time and effort to put this informative
    article together. I once again find myself spending way too much time both
    reading and commenting. But so what, it was still worthwhile!

  14. Jogue no cassino aprovado Blaze

  15. review表示:

    At this time it appears like BlogEngine is the preferred blogging platform out there right now. (from what I’ve read) Is that what you’re using on your blog?

  16. Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you could do with a few pics to drive the message home a little bit, but other than that, this is fantastic blog. An excellent read. I will certainly be back.

  17. Great post. I was checking continuously this blog and I’m impressed! Extremely helpful info particularly the last part 🙂 I care for such info much. I was looking for this certain information for a very long time. Thank you and best of luck.

  18. A person essentially help to make seriously posts I would state. This is the first time I frequented your website page and thus far? I surprised with the research you made to create this particular publish amazing. Magnificent job!

  19. 4 Futons表示:

    Fantastic website. Lots of useful information here. I?m sending it to several pals ans also sharing in delicious. And certainly, thanks for your sweat!

  20. You really make it appear so easy together with your presentation however I find this topic to be really something that I think I might never understand. It kind of feels too complex and extremely large for me. I am having a look forward to your next submit, I?ll attempt to get the hold of it!

  21. Jetta表示:

    This is the perfect blog for everyone who would like to find out about this topic.
    You realize so much its almost tough to argue with you (not that
    I really will need to…HaHa). You definitely put a brand new spin on a
    subject that’s been discussed for ages. Excellent stuff, just excellent!

  22. эффективно,
    Современное оборудование и материалы, для крепких и здоровых зубов,
    Профессиональное лечение и консультации, для вашего уверенного выбора,
    Комфортные условия и дружественный персонал, для вашей радости и улыбки,
    Комплексное восстановление утраченных зубов, для вашего комфорта и уверенности,
    Индивидуальный план лечения и профилактики, для вашего долгосрочного удовлетворения,
    Индивидуальный план лечения для каждого пациента, для вашего здоровья и благополучия
    зуби лікування зуби лікування .

  23. Marguerite表示:

    Its not my first time to pay a visit this web site, i am browsing this site dailly
    and take nice data from here daily.

  24. I like what you guys are usually up too. Such clever work and reporting!
    Keep up the fantastic works guys I’ve included you guys to blogroll.

  25. Sweet blog! I found it while searching on Yahoo News.
    Do you have any suggestions on how to get listed in Yahoo
    News? I’ve been trying for a while but I never seem to get
    there! Appreciate it

  26. sex dolls表示:

    Superb blog you have here but I was wondering if you knew of any forums that cover the same topics discussed
    in this article? I’d really like to be a part of online community where I
    can get responses from other experienced people that share the same interest.
    If you have any recommendations, please let me know.
    Thanks!

  27. dildos表示:

    Thanks a bunch for sharing this with all of us you actually
    understand what you are talking about! Bookmarked. Please additionally talk over with my site =).
    We can have a link change contract between us

  28. Ganhe no cassino mais confiavel Blaze

  29. fake bags表示:

    Hi to all, the contents existing at this web page are truly remarkable for people knowledge, well, keep up the nice work fellows.

  30. Отличный сайт! Всем рекомендую! Тут Вы можете найтилучшие брокеры для скальпинга

發佈留言

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