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

13,970 Responses

  1. I think other site proprietors should take this web site as an model, very clean and fantastic user genial style and design, as well as the content. You are an expert in this topic!

  2. DominicJaw表示:

    mexican border pharmacies shipping to usa: mexican online pharmacies prescription drugs – pharmacies in mexico that ship to usa

  3. Generally I do not read article on blogs, but I wish to say that this write-up very forced me to try and do it! Your writing style has been surprised me. Thanks, very nice article.

  4. Nelsonbluck表示:

    mexico drug stores pharmacies: mexican drugstore online – buying prescription drugs in mexico online

  5. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your webpage? My blog is in the very same area of interest as yours and my visitors would definitely benefit from a lot of the information you provide here. Please let me know if this ok with you. Cheers!

  6. okmark your blog and check again here regularly. I’m quite certain I will learn lots of new stuff right here! Good luck for the next!

  7. Arnoldten表示:

    mexico pharmacies prescription drugs medicine in mexico pharmacies mexico drug stores pharmacies

  8. I would like to add if you do not actually have an insurance policy or perhaps you do not take part in any group insurance, you might well really benefit from seeking the assistance of a health agent. Self-employed or those with medical conditions ordinarily seek the help of an health insurance dealer. Thanks for your post.

  9. Thank you for another informative website. Where else could I get that type of info written in such an ideal way? I have a project that I’m just now working on, and I have been on the look out for such info.

  10. magnificent post, very informative. I’m wondering why the other experts of this sector do not notice this. You must continue your writing. I’m confident, you’ve a huge readers’ base already!

  11. Incredible! This blog looks just like my old one! It’s on a completely different subject but it has pretty much the same page layout and design. Great choice of colors!

  12. I?m now not certain where you’re getting your information, however great topic. I needs to spend some time studying more or figuring out more. Thanks for great info I was searching for this information for my mission.

  13. Jbpnzd表示:

    terazosin 1mg without prescription – hytrin uk purchase priligy pill

  14. You could certainly see your expertise in the paintings you write. The sector hopes for even more passionate writers like you who aren’t afraid to mention how they believe. Always go after your heart.

  15. Spot on with this write-up, I truly assume this web site wants rather more consideration. I?ll in all probability be once more to learn way more, thanks for that info.

  16. WayneCoirl表示:

    mexican pharmaceuticals online: purple pharmacy mexico price list – medication from mexico pharmacy

  17. DominicJaw表示:

    medication from mexico pharmacy: mexico drug stores pharmacies – reputable mexican pharmacies online

  18. Hello! This post couldn’t be written any better! Reading this post reminds me of my previous room mate! He always kept chatting about this. I will forward this page to him. Fairly certain he will have a good read. Thank you for sharing!

  19. What i do not realize is actually how you’re not actually much more well-liked than you might be now. You’re so intelligent. You realize thus considerably relating to this subject, produced me personally consider it from a lot of varied angles. Its like women and men aren’t fascinated unless it?s one thing to do with Lady gaga! Your own stuffs nice. Always maintain it up!

  20. Nelsonbluck表示:

    reputable mexican pharmacies online: mexico drug stores pharmacies – pharmacies in mexico that ship to usa

  21. This article is absolutely incredible! The author has done a fantastic job of presenting the information in an engaging and enlightening manner. I can’t thank her enough for sharing such priceless insights that have definitely enlightened my knowledge in this subject area. Hats off to him for creating such a masterpiece!

  22. Once I originally commented I clicked the -Notify me when new feedback are added- checkbox and now each time a remark is added I get four emails with the identical comment. Is there any manner you possibly can remove me from that service? Thanks!

  23. You could certainly see your enthusiasm in the work you write. The world hopes for more passionate writers like you who are not afraid to say how they believe. Always go after your heart.

  24. Arnoldten表示:

    best online pharmacies in mexico mexican mail order pharmacies medicine in mexico pharmacies

  25. Hello there! I know this is kind of off topic but I was wondering if you knew where I could find a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one? Thanks a lot!

  26. anime master表示:

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

  27. This is without a doubt one of the best articles I’ve read on this topic! The author’s comprehensive knowledge and enthusiasm for the subject are apparent in every paragraph. I’m so appreciative for coming across this piece as it has enhanced my understanding and ignited my curiosity even further. Thank you, author, for investing the time to produce such a phenomenal article!

  28. There are definitely a whole lot of details like that to take into consideration. That may be a great point to carry up. I supply the ideas above as basic inspiration however clearly there are questions just like the one you convey up the place a very powerful factor will probably be working in honest good faith. I don?t know if best practices have emerged around issues like that, however I’m certain that your job is clearly recognized as a good game. Each boys and girls feel the affect of only a second?s pleasure, for the remainder of their lives.

  29. This design is incredible! You most certainly know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Great job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!

  30. Thanks for the ideas you share through this web site. In addition, lots of young women that become pregnant will not even try and get medical health insurance because they are full of fearfulness they would not qualify. Although a few states now require that insurers give coverage irrespective of the pre-existing conditions. Costs on these guaranteed plans are usually higher, but when taking into consideration the high cost of health care bills it may be any safer route to take to protect a person’s financial future.

發佈留言

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