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

11,440 Responses

  1. My brother suggested I might like this website. He was entirely right. This post actually made my day. You cann’t imagine just how much time I had spent for this information! Thanks!

  2. Appreciating the commitment you put into your site and detailed information you provide. It’s awesome to come across a blog every once in a while that isn’t the same unwanted rehashed information. Wonderful read! I’ve saved your site and I’m including your RSS feeds to my Google account.

  3. anime master表示:

    Great post. I was checking continuously this blog and I am impressed! Very helpful info specially the last part 🙂 I care for such information a lot. I was looking for this particular info for a long time. Thank you and best of luck.

  4. WayneCoirl表示:

    mexican mail order pharmacies: mexican mail order pharmacies – mexican pharmaceuticals online

  5. Magnificent beat ! I would like to apprentice while you amend your web site, how could i subscribe for a blog web site? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear idea

  6. DominicJaw表示:

    buying prescription drugs in mexico: buying from online mexican pharmacy – mexican border pharmacies shipping to usa

  7. It?s onerous to seek out knowledgeable individuals on this topic, however you sound like you understand what you?re speaking about! Thanks

  8. One thing is one of the most popular incentives for making use of your card is a cash-back as well as rebate supply. Generally, you’ll have access to 1-5 back in various buying. Depending on the credit card, you may get 1 in return on most buying, and 5 again on purchases made on convenience stores, filling stations, grocery stores as well as ‘member merchants’.

  9. Another thing I have really noticed is for many people, below-average credit is the response to circumstances further than their control. By way of example they may are already saddled through an illness so they really have higher bills going to collections. It may be due to a job loss or perhaps the inability to work. Sometimes divorce or separation can send the financial circumstances in an opposite direction. Many thanks sharing your opinions on this blog site.

  10. Undeniably believe that which you said. Your favorite reason seemed to be on the internet the easiest thing to be aware of. I say to you, I definitely get irked while people think about worries that they plainly do not know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side effect , people can take a signal. Will probably be back to get more. Thanks

  11. Undeniably believe that which you stated. Your favorite reason seemed to be on the net the easiest thing to be aware of. I say to you, I definitely get irked while people consider worries that they just don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people could take a signal. Will probably be back to get more. Thanks

  12. Spot on with this write-up, I actually think this website needs rather more consideration. I?ll most likely be once more to learn rather more, thanks for that info.

  13. Nelsonbluck表示:

    п»їbest mexican online pharmacies: medication from mexico pharmacy – mexican drugstore online

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

  15. of course like your website but you have to check the spelling on several of your posts. A number of them are rife with spelling issues and I find it very troublesome to tell the truth nevertheless I will surely come back again.

  16. Wow! This can be one particular of the most useful blogs We’ve ever arrive across on this subject. Basically Magnificent. I am also a specialist in this topic therefore I can understand your hard work.

  17. Arnoldten表示:

    pharmacies in mexico that ship to usa purple pharmacy mexico price list mexican border pharmacies shipping to usa

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

  19. You really make it seem so easy with your presentation but I find this topic to be actually something that I think I would never understand. It seems too complicated and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it!

  20. I have observed that car insurance providers know the vehicles which are susceptible to accidents and other risks. Additionally , they know what type of cars are susceptible to higher risk as well as the higher risk they have the higher the premium amount. Understanding the basic basics involving car insurance can help you choose the right form of insurance policy that can take care of your preferences in case you become involved in any accident. Thank you sharing the particular ideas on your own blog.

  21. Thanks for the tips you have shared here. Something important I would like to talk about is that laptop memory needs generally go up along with other developments in the technological know-how. For instance, as soon as new generations of processors are made in the market, there is certainly usually a corresponding increase in the scale calls for of both the computer system memory plus hard drive room. This is because software program operated by means of these processors will inevitably rise in power to use the new technology.

  22. Greetings from Los angeles! I’m bored at work so I decided to check out your website on my iphone during lunch break. I really like the info you present here and can’t wait to take a look when I get home. I’m amazed at how quick your blog loaded on my cell phone .. I’m not even using WIFI, just 3G .. Anyhow, awesome site!

  23. Thanks for the ideas you are revealing on this web site. Another thing I would like to say is that getting hold of some copies of your credit profile in order to check out accuracy of each and every detail may be the first motion you have to accomplish in credit repair. You are looking to thoroughly clean your credit file from damaging details flaws that mess up your credit score.

  24. Woah! I’m really loving the template/theme of this site. It’s simple, yet effective. A lot of times it’s very difficult to get that “perfect balance” between superb usability and visual appeal. I must say you have done a great job with this. Also, the blog loads very quick for me on Opera. Superb Blog!

  25. Heya i?m for the first time here. I came across this board and I find It truly useful & it helped me out a lot. I hope to give something back and aid others like you helped me.

  26. Virtually all of the things you point out is supprisingly legitimate and that makes me wonder the reason why I hadn’t looked at this in this light previously. This particular article really did switch the light on for me personally as far as this topic goes. However there is actually just one issue I am not necessarily too comfy with so while I make an effort to reconcile that with the central idea of the position, permit me see just what the rest of the subscribers have to say.Well done.

  27. The things i have generally told individuals is that while looking for a good on the net electronics shop, there are a few aspects that you have to think about. First and foremost, you should really make sure to find a reputable as well as reliable shop that has received great evaluations and rankings from other consumers and marketplace analysts. This will make sure that you are getting through with a well-known store to provide good assistance and support to it’s patrons. Thank you for sharing your opinions on this blog.

  28. Lazrheh表示:

    Добрый день!
    Приобрести диплом любого ВУЗа.
    ls.co-x.ru/2024/07/04/kak-nayti-nadezhnyy-onlayn-magazin-s-obshirnym-assortimentom-diplomov

  29. Diplomi_rnEa表示:

    Здравствуйте!
    Купить документ о получении высшего образования можно в нашей компании.
    asxdiplomik.com/kupit-diplom-kandidata-nauk

發佈留言

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