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

35,136 Responses

  1. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three e-mails with the same comment. Is there any way you can remove me from that service? Thank you!

  2. Trenterone表示:

    buying from online mexican pharmacy: purple pharmacy mexico price list – Agb Mexico Pharm

  3. It needs to go on the body of the car smoothly because bubbles or ripples end up weakening the paint.

  4. EdwinWency表示:

    canadian pharmacy meds reviews: legitimate canadian online pharmacies – canada discount pharmacy

  5. You can certainly see your enthusiasm in the work you write. The world hopes for even more passionate writers like you who are not afraid to say how they believe. All the time go after your heart.

  6. ChesterFus表示:

    canadian pharmacy meds review: GoCanadaPharm – canadian online pharmacy

  7. MatthewTek表示:

    https://gocanadapharm.com/# canadian mail order pharmacy

  8. Thanks for your content. One other thing is that if you are selling your property all on your own, one of the difficulties you need to be mindful of upfront is just how to deal with property inspection records. As a FSBO vendor, the key concerning successfully switching your property as well as saving money in real estate agent commissions is expertise. The more you are aware of, the simpler your home sales effort are going to be. One area exactly where this is particularly essential is home inspections.

  9. My brother suggested I might like this web site. He was totally right. This post actually made my day. You can not imagine simply how much time I had spent for this info! Thanks!

  10. Heya i am for the first time here. I came across this board and I find It really useful & it helped me out much. I hope to give something back and aid others like you aided me.

  11. What i do not understood is in reality how you’re not actually much more well-liked than you might be now. You’re very intelligent. You know thus significantly in terms of this subject, produced me in my view believe it from so many varied angles. Its like men and women don’t seem to be fascinated until it?s one thing to accomplish with Woman gaga! Your own stuffs outstanding. All the time take care of it up!

  12. ChesterFus表示:

    safe canadian pharmacy: legal canadian pharmacy online – the canadian pharmacy

  13. I just added this weblog to my rss reader, great stuff. Can not get enough!

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

  15. EdwinWency表示:

    best canadian online pharmacy: go canada pharm – canadian online pharmacy reviews

  16. Hi my friend! I want to say that this post is amazing, nice written and include almost all vital infos. I would like to see more posts like this.

  17. ChesterFus表示:

    Online medicine order: indian pharmacies safe – www india pharm

  18. One thing I want to say is the fact car insurance canceling is a hated experience and if you’re doing the right things as being a driver you simply won’t get one. A lot of people do obtain the notice that they have been officially dumped by their particular insurance company they have to fight to get extra insurance after the cancellation. Inexpensive auto insurance rates usually are hard to get after the cancellation. Knowing the main reasons pertaining to auto insurance termination can help drivers prevent completely losing in one of the most crucial privileges obtainable. Thanks for the thoughts shared by means of your blog.

  19. Trenterone表示:

    safe online pharmacies in canada: go canada pharm – canada drugs

  20. MatthewTek表示:

    http://gocanadapharm.com/# canadian pharmacy in canada

  21. Hey just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same outcome.

  22. Pretty nice post. I just stumbled upon your weblog and wished to say that I have really enjoyed browsing your blog posts. After all I?ll be subscribing to your feed and I hope you write again soon!

  23. RobertPaync表示:

    Agb Mexico Pharm mexico pharmacies prescription drugs buying prescription drugs in mexico

  24. Excellent site. A lot of useful information here. I am sending it to some friends ans also sharing in delicious. And obviously, thanks for your effort!

  25. MatthewTek表示:

    https://gocanadapharm.com/# canadian pharmacy service

  26. ChesterFus表示:

    www india pharm: www india pharm – www india pharm

  27. What I have seen in terms of pc memory is the fact there are features such as SDRAM, DDR and the like, that must fit the features of the mother board. If the personal computer’s motherboard is reasonably current and there are no os issues, updating the memory literally normally takes under one hour. It’s among the list of easiest personal computer upgrade processes one can imagine. Thanks for giving your ideas.

  28. RobertPaync表示:

    mexican online pharmacies prescription drugs Agb Mexico Pharm buying from online mexican pharmacy

  29. I?d must check with you here. Which isn’t one thing I often do! I enjoy studying a put up that may make people think. Additionally, thanks for allowing me to remark!

發佈回覆給「หลุดนักเรียน」的留言 取消回覆

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