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

  1. Heya i am for the first time here. I found 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 aided me.

  2. Cassino que voce vai adorar Blaze

  3. Thanks for the interesting things you have exposed in your article. One thing I’d like to reply to is that FSBO human relationships are built as time passes. By presenting yourself to the owners the first end of the week their FSBO is definitely announced, prior to a masses start out calling on Mon, you create a good association. By sending them equipment, educational products, free records, and forms, you become a good ally. By subtracting a personal desire for them in addition to their predicament, you create a solid link that, on most occasions, pays off as soon as the owners opt with a broker they know as well as trust — preferably you actually.

  4. Hi! Would you mind if I share your blog with my facebook group? There’s a lot of people that I think would really enjoy your content. Please let me know. Thank you

  5. hey there and thank you for your information ? I?ve certainly picked up anything new from right here. I did however expertise a few technical issues using this site, since I experienced to reload the site a lot of times previous to I could get it to load correctly. I had been wondering if your web hosting is OK? Not that I am complaining, but slow loading instances times will very frequently affect your placement in google and can damage your high quality score if ads and marketing with Adwords. Anyway I am adding this RSS to my email and can look out for much more of your respective fascinating content. Ensure that you update this again soon..

  6. It?s really a great and helpful piece of info. I am happy that you simply shared this helpful info with us. Please stay us informed like this. Thanks for sharing.

  7. I have been exploring for a little bit for any high quality articles or blog posts on this sort of space . Exploring in Yahoo I ultimately stumbled upon this web site. Reading this info So i am satisfied to express that I have a very good uncanny feeling I found out just what I needed. I most certainly will make certain to do not overlook this website and give it a glance on a continuing basis.

  8. I truly appreciate this post. I have been looking everywhere for this! Thank goodness I found it on Bing. You’ve made my day! Thx again

  9. Yesterday, while I was at work, my sister stole my iPad and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is entirely off topic but I had to share it with someone!

  10. pyt twerk表示:

    Nice post. I learn something more difficult on completely different blogs everyday. It is going to all the time be stimulating to read content material from other writers and apply a little bit something from their store. I?d want to make use of some with the content material on my blog whether or not you don?t mind. Natually I?ll offer you a link in your web blog. Thanks for sharing.

  11. Thanks for the suggestions about credit repair on this particular site. The thing I would tell people is usually to give up the particular mentality that they’ll buy now and pay out later. Like a society we tend to do that for many factors. This includes holidays, furniture, in addition to items we want. However, you need to separate a person’s wants out of the needs. When you’re working to fix your credit score make some trade-offs. For example you possibly can shop online to economize or you can click on second hand retailers instead of high-priced department stores with regard to clothing.

  12. Thanks for your useful article. One other problem is that mesothelioma cancer is generally a result of the inhalation of dust from asbestos, which is a dangerous material. It really is commonly witnessed among employees in the construction industry who may have long contact with asbestos. It can be caused by living in asbestos protected buildings for years of time, Genetic makeup plays a crucial role, and some consumers are more vulnerable to the risk in comparison with others.

  13. porn twerking表示:

    I’m impressed by the quality of this content! The author has clearly put a tremendous amount of effort into exploring and arranging the information. It’s refreshing to come across an article that not only provides useful information but also keeps the readers engaged from start to finish. Kudos to her for producing such a masterpiece!

  14. I loved as much as you’ll receive performed right here. The comic strip is attractive, your authored material stylish. nonetheless, you command get got an edginess over that you would like be turning in the following. ill no doubt come more formerly again as exactly the same nearly a lot ceaselessly inside case you protect this hike.

  15. becky g twerk表示:

    One other issue is when you are in a circumstance where you do not possess a co-signer then you may really need to try to exhaust all of your school funding options. You can get many funds and other scholarships or grants that will present you with finances to support with university expenses. Thanks alot : ) for the post.

  16. sexy twerking表示:

    Also I believe that mesothelioma is a exceptional form of cancers that is commonly found in these previously familiar with asbestos. Cancerous tissue form inside mesothelium, which is a defensive lining which covers almost all of the body’s bodily organs. These cells typically form while in the lining of your lungs, abdomen, or the sac which actually encircles one’s heart. Thanks for discussing your ideas.

  17. One other issue is that if you are in a circumstances where you do not possess a co-signer then you may really want to try to wear out all of your school funding options. You will discover many grants or loans and other grants that will supply you with funding to help with school expenses. Thanks a lot for the post.

  18. My brother suggested I would possibly like this blog. He used to be totally right. This submit actually made my day. You can not believe simply how so much time I had spent for this info! Thanks!

  19. Attractive element of content. I just stumbled upon your website and in accession capital to claim that I acquire actually enjoyed account your blog posts. Anyway I will be subscribing to your augment and even I achievement you get admission to consistently quickly.

  20. Thanks alot : ) for your post. I’d prefer to comment that the tariff of car insurance differs from one coverage to another, since there are so many different facets which bring about the overall cost. For instance, the brand name of the automobile will have a tremendous bearing on the price tag. A reliable old family automobile will have a more economical premium than the usual flashy racecar.

  21. A melhor opcao para jogos de azar Blaze

  22. I’m impressed by the quality of this content! The author has clearly put a tremendous amount of effort into researching and arranging the information. It’s inspiring to come across an article that not only offers helpful information but also keeps the readers hooked from start to finish. Kudos to her for producing such a brilliant work!

  23. Seu cassino da sorte espera por voce Blaze

  24. milf twerking表示:

    Hey there are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you need any coding expertise to make your own blog? Any help would be really appreciated!

  25. Hello! I’ve been following your web site for some time now and finally got the courage to go ahead and give you a shout out from Dallas Tx! Just wanted to say keep up the excellent work!

  26. Thanks for this excellent article. Also a thing is that almost all digital cameras come equipped with any zoom lens that allows more or less of any scene to become included by means of ‘zooming’ in and out. These kinds of changes in {focus|focusing|concentration|target|the a**** length are reflected inside the viewfinder and on big display screen right at the back of the specific camera.

  27. ufo twerk表示:

    I have realized that over the course of creating a relationship with real estate homeowners, you’ll be able to get them to understand that, in most real estate exchange, a commission is paid. Ultimately, FSBO sellers tend not to “save” the commission payment. Rather, they struggle to earn the commission simply by doing an agent’s task. In accomplishing this, they expend their money and time to execute, as best they can, the tasks of an adviser. Those obligations include disclosing the home via marketing, presenting the home to buyers, creating a sense of buyer emergency in order to make prompt an offer, organizing home inspections, controlling qualification investigations with the mortgage lender, supervising maintenance, and aiding the closing.

  28. I don?t even understand how I ended up right here, but I believed this post used to be great. I do not know who you might be however definitely you’re going to a well-known blogger for those who aren’t already 😉 Cheers!

  29. Thank you for sharing these kind of wonderful content. In addition, the optimal travel plus medical insurance strategy can often relieve those concerns that come with journeying abroad. Some sort of medical emergency can rapidly become very costly and that’s likely to quickly place a financial load on the family’s finances. Setting up in place the perfect travel insurance program prior to setting off is well worth the time and effort. Cheers

  30. One more thing. It’s my opinion that there are numerous travel insurance web sites of reputable companies that allow you enter holiday details and get you the rates. You can also purchase an international holiday insurance policy on-line by using your own credit card. Everything you need to do would be to enter all travel specifics and you can see the plans side-by-side. Just find the program that suits your finances and needs then use your bank credit card to buy the idea. Travel insurance online is a good way to start looking for a respected company with regard to international travel cover. Thanks for revealing your ideas.

發佈留言

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