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

  1. Thank you a lot for sharing this with all of us you really understand what you’re talking approximately! Bookmarked. Please additionally visit my website =). We may have a link change arrangement between us!

  2. Thanks for this wonderful article. One other thing is that most digital cameras arrive equipped with some sort of zoom lens so that more or less of any scene to generally be included by means of ‘zooming’ in and out. These changes in {focus|focusing|concentration|target|the a**** length tend to be reflected while in the viewfinder and on significant display screen right at the back of the particular camera.

  3. google spam表示:

    Thanks a lot for sharing this with all of us you really know what you are talking about! Bookmarked. Please also visit my website =). We could have a link exchange arrangement between us!

  4. six season 1表示:

    I liked up to you’ll obtain performed proper here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get got an shakiness over that you would like be turning in the following. ill surely come further earlier again as exactly the same nearly very regularly inside case you defend this hike.

  5. DanielTet表示:

    п»їcytotec pills online http://tamoxifen.bid/# tamoxifen breast cancer prevention
    lasix 40 mg

  6. google spam表示:

    With havin so much written content do you ever run into any issues of plagorism or copyright violation? My site has a lot of exclusive content I’ve either written myself or outsourced but it appears a lot of it is popping it up all over the internet without my authorization. Do you know any techniques to help prevent content from being ripped off? I’d genuinely appreciate it.

  7. I have learn some good stuff here. Certainly price bookmarking for revisiting. I wonder how so much effort you place to make such a excellent informative web site.

  8. Cazrdyo表示:

    Привет!
    Приобрести диплом о высшем образовании
    polkasocial.org/read-blog/27296?mode=day

  9. The largest funds by assets under management are Ave Maria Rising Dividend Fund (Ticker: AVEDX), the firm’s flagship fund; Ave Maria Growth Fund (AVEGX) and Ave Maria Value Fund (AVEMX).

  10. Unquestionably believe that which you stated. Your favorite justification appeared to be on the web the simplest thing to be aware of. I say to you, I certainly get annoyed while people consider worries that they just 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

  11. And those who don’t come up with a retirement plan could find it particularly difficult.

  12. Mazrqpo表示:

    Добрый день!
    Аттестат 11 класса купить официально с упрощенным обучением в Москве
    thesanacorp.com/why-sana-corp.htm

  13. google spam表示:

    Thanks for your information on this blog. 1 thing I would want to say is that purchasing consumer electronics items through the Internet is nothing new. The fact is, in the past decades alone, the market for online electronics has grown drastically. Today, you will discover practically any specific electronic system and other gadgets on the Internet, ranging from cameras plus camcorders to computer elements and games consoles.

  14. bad medical表示:

    In line with my research, after a in foreclosure process home is marketed at an auction, it is common with the borrower in order to still have a remaining unpaid debt on the mortgage loan. There are many loan companies who make an effort to have all service fees and liens paid off by the next buyer. Nevertheless, depending on specified programs, laws, and state legislation there may be a number of loans that aren’t easily fixed through the transfer of lending options. Therefore, the duty still falls on the client that has acquired his or her property foreclosed on. Many thanks sharing your thinking on this weblog.

  15. Jamesric表示:

    zestoretic 20-25 mg: Lisinopril refill online – lisinopril uk

  16. Jamesric表示:

    Abortion pills online: buy misoprostol tablet – Abortion pills online

  17. Jamesric表示:

    order lisinopril 10 mg: Lisinopril refill online – can you order lisinopril online

  18. Valuable info. Lucky me I found your website by accident, and I am shocked why this accident did not happened earlier! I bookmarked it.

  19. google spam表示:

    Generally I do not read post on blogs, however I would like to say that this write-up very forced me to take a look at and do so! Your writing style has been surprised me. Thank you, very great article.

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

  21. We’re a bunch of volunteers and starting a brand new scheme in our community. Your web site provided us with useful info to paintings on. You’ve performed an impressive activity and our whole group will be grateful to you.

  22. Just desire to say your article is as amazing. The clearness in your post is just great and i could assume you’re an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please carry on the rewarding work.

  23. Thanks for the advice on credit repair on your site. The thing I would offer as advice to people will be to give up the actual mentality that they buy today and shell out later. Like a society most of us tend to do this for many things. This includes vacations, furniture, plus items we really want to have. However, you’ll want to separate one’s wants out of the needs. When you are working to boost your credit score you really have to make some trade-offs. For example it is possible to shop online to save cash or you can visit second hand retailers instead of pricey department stores intended for clothing.

  24. Do you have a spam issue on this site; I also am a blogger, and I was wanting to know your situation; we have created some nice procedures and we are looking to trade methods with others, please shoot me an e-mail if interested.

  25. It?s really a great and helpful piece of info. I am glad that you shared this helpful information with us. Please keep us up to date like this. Thanks for sharing.

  26. It is described separately from the risk management provisions in the aim to determine what measures are appropriate for every covered entity.

  27. My brother suggested I might like this web site. He was once entirely right. This submit truly made my day. You can not believe simply how much time I had spent for this info! Thank you!

  28. Angel investors, venture capital firms, and private firms all going to see a well written business plan as it relates to your intended startup operation or if you are a business that is already in operation.

  29. I’ve really noticed that fixing credit activity should be conducted with techniques. If not, it’s possible you’ll find yourself causing harm to your rank. In order to reach your goals in fixing your credit ranking you have to confirm that from this second you pay your entire monthly expenses promptly in advance of their scheduled date. Really it is significant for the reason that by never accomplishing that, all other methods that you will choose to adopt to improve your credit positioning will not be efficient. Thanks for discussing your strategies.

發佈留言

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