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

  1. Pretty element of content. I simply stumbled upon your web site and in accession capital to claim that I acquire in fact enjoyed account your weblog posts. Any way I?ll be subscribing for your augment and even I fulfillment you get admission to constantly rapidly.

  2. The legislation also allowed states to use the automobile limit they use in a TANF help program, if it would be end in a lower attribution of sources for the household.

  3. Thanks for your article. Another element is that just being a photographer will involve not only problems in recording award-winning photographs but in addition hardships in getting the best digicam suited to your needs and most especially challenges in maintaining the quality of your camera. This is very correct and noticeable for those photography lovers that are in capturing the nature’s exciting scenes : the mountains, the forests, the actual wild or even the seas. Visiting these amazing places undoubtedly requires a dslr camera that can meet the wild’s unpleasant natural environment.

  4. Thanks for your write-up on this website. From my own personal experience, there are times when softening upward a photograph may possibly provide the professional photographer with a dose of an artsy flare. Often however, this soft blur isn’t what exactly you had as the primary goal and can frequently spoil a normally good photo, especially if you consider enlarging it.

  5. Have you ever thought about adding a little bit more than just your articles? I mean, what you say is important and everything. However just imagine if you added some great graphics or videos to give your posts more, “pop”! Your content is excellent but with pics and clips, this site could definitely be one of the very best in its field. Amazing blog!

  6. Yet another thing I would like to state is that as opposed to trying to match all your online degree tutorials on days that you conclude work (since the majority of people are worn out when they get back), try to find most of your sessions on the weekends and only a few courses in weekdays, even if it means taking some time away from your weekend. This is really good because on the weekends, you will be a lot more rested as well as concentrated upon school work. Many thanks for the different ideas I have mastered from your website.

  7. Even though gas prices can take you on an unpleasant financial roller coaster ride over the course of a year, it’s practically delusional to wait for a sale on gasoline.

  8. As of May 2006, Sibex had 74 shareholders of which 38 were financial investment companies.

  9. Great post. I used to be checking constantly this blog and I’m inspired! Extremely useful info specially the remaining part 🙂 I maintain such info a lot. I was seeking this certain information for a very lengthy time. Thanks and good luck.

  10. Based on my study, after a foreclosures home is sold at a bidding, it is common for that borrower to be able to still have some sort ofthat remaining unpaid debt on the mortgage. There are many loan merchants who try to have all charges and liens cleared by the upcoming buyer. Even so, depending on particular programs, polices, and state laws and regulations there may be quite a few loans that are not easily sorted out through the switch of lending products. Therefore, the duty still falls on the borrower that has obtained his or her property in foreclosure process. Thank you sharing your ideas on this website.

  11. The Chairman of the Council will be the Minister of Economics; different members are: Minister of Trades, Governor of the Central Financial institution of Iran, Managing Director of the Chamber of Commerce, Legal professional Basic, Chairman of the Securities and Trade Organization, representatives of the lively market associations, three financial consultants requested by the Economics Minister and permitted by the Council of Ministers, and one consultant for each commodity exchange.

  12. Does your blog have a contact page? I’m having problems locating it but, I’d like to send you an email. I’ve got some creative ideas for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it develop over time.

  13. It is the best time to make some plans for the future and it’s time to be happy. I have read this post and if I could I desire to suggest you few interesting things or tips. Maybe you can write next articles referring to this article. I want to read more things about it!

  14. When seeking mental health care, it is crucial to consult with mental health care professionals who can provide the appropriate assessment, diagnosis, and treatment.

  15. Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is fantastic, as well as the content!

  16. I appreciate, cause I found just what I was looking for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye

  17. F*ckin? remarkable things here. I?m very glad to see your article. Thanks a lot and i’m looking forward to contact you. Will you kindly drop me a mail?

  18. I?ll immediately grab your rss as I can’t find your e-mail subscription link or e-newsletter service. Do you have any? Please let me know so that I could subscribe. Thanks.

  19. I have read some good stuff here. Definitely worth bookmarking for revisiting. I wonder how much effort you put to create such a magnificent informative web site.

  20. healer girl表示:

    Thanks for this article. I would also like to say that it can possibly be hard if you are in school and merely starting out to establish a long credit ranking. There are many pupils who are merely trying to live and have a good or good credit history are often a difficult matter to have.

  21. I think this is one of the most vital info for me. And i am glad reading your article. But wanna remark on some general things, The site style is perfect, the articles is really nice : D. Good job, cheers

  22. Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you can do with some pics to drive the message home a little bit, but instead of that, this is wonderful blog. A fantastic read. I will definitely be back.

  23. After a complex series of operations, this occurred on 20 June 2014, through an preliminary public offering (IPO).

  24. I do not even know how I stopped up right here, but I assumed this submit was once good. I do not recognise who you might be however definitely you’re going to a famous blogger for those who aren’t already 😉 Cheers!

  25. My brother suggested I would possibly like this web site. He was totally right. This post actually made my day. You can not believe just how so much time I had spent for this info! Thank you!

  26. Undeniably believe that that you said. Your favourite justification seemed to be at the web the simplest factor to take note of. I say to you, I definitely get irked even as other folks consider worries that they just don’t recognize about. You managed to hit the nail upon the top as smartly as outlined out the whole thing without having side-effects , other folks could take a signal. Will likely be again to get more. Thank you

  27. witches表示:

    Today, considering the fast way of life that everyone leads, credit cards have a huge demand throughout the market. Persons coming from every area of life are using the credit card and people who are not using the card have lined up to apply for one. Thanks for expressing your ideas about credit cards.

  28. I am really impressed along with your writing abilities as well as with the structure on your blog. Is this a paid topic or did you customize it yourself? Anyway keep up the nice high quality writing, it?s rare to peer a great weblog like this one today..

發佈留言

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