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

  1. This really answered my downside, thanks!

  2. Hello, i think that i saw you visited my weblog so i came to ?return the favor?.I am attempting to find things to enhance my website!I suppose its ok to use some of your ideas!!

  3. Arnoldten表示:

    п»їbest mexican online pharmacies mexican pharmacy mexican mail order pharmacies

  4. Hello! I know this is somewhat off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having problems finding one? Thanks a lot!

  5. I have noticed that good real estate agents all over the place are Promoting. They are acknowledging that it’s in addition to placing a sign in the front area. It’s really about building human relationships with these vendors who sooner or later will become buyers. So, once you give your time and efforts to helping these vendors go it alone — the “Law involving Reciprocity” kicks in. Great blog post.

  6. thesameroxm表示:

    Good blog! I truly love how it is simple on my eyes and the data are well written. I’m wondering how I could be notified when a new post has been made. I have subscribed to your RSS feed which must do the trick! Have a great day!

  7. ixxx表示:

    I have learn some excellent stuff here. Definitely value bookmarking for revisiting. I wonder how so much effort you set to make any such fantastic informative website.

  8. vk onlyfans表示:

    Hello there, I found your blog via Google while looking for a related topic, your website came up, it looks good. I’ve bookmarked it in my google bookmarks.

  9. mewa表示:

    Woah! I’m really enjoying the template/theme of this site. It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between usability and visual appeal. I must say you have done a amazing job with this. Additionally, the blog loads super quick for me on Internet explorer. Outstanding Blog!

  10. WayneCoirl表示:

    buying prescription drugs in mexico: mexican online pharmacies prescription drugs – medication from mexico pharmacy

  11. WONDERFUL Post.thanks for share..more wait .. ?

  12. Отличный сайт! Всем рекомендую!пиастрикс казино

  13. Nelsonbluck表示:

    purple pharmacy mexico price list: best online pharmacies in mexico – mexico drug stores pharmacies

  14. Howdy! Someone in my Myspace group shared this website with us so I came to check it out. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers! Great blog and superb style and design.

  15. Hey There. I found your blog the usage of msn. This is an extremely neatly written article. I?ll be sure to bookmark it and return to read extra of your helpful information. Thanks for the post. I will definitely comeback.

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

  17. uinkuru表示:

    Hello, you used to write excellent, but the last few posts have been kinda boring? I miss your great writings. Past few posts are just a little bit out of track! come on!

  18. DominicJaw表示:

    best online pharmacies in mexico: mexico drug stores pharmacies – buying prescription drugs in mexico

  19. I’ve learned many important things by means of your post. I’d also like to say that there can be situation that you will have a loan and never need a cosigner such as a Fed Student Support Loan. However, if you are getting credit through a standard financier then you need to be able to have a co-signer ready to allow you to. The lenders will certainly base their own decision over a few elements but the most important will be your credit ratings. There are some loan companies that will as well look at your work history and choose based on that but in many cases it will depend on your ranking.

  20. I have noticed that car insurance businesses know the motors which are at risk of accidents and also other risks. Additionally , they know what form of cars are given to higher risk and also the higher risk they’ve got the higher the actual premium amount. Understanding the simple basics associated with car insurance will allow you to choose the right sort of insurance policy that should take care of the needs you have in case you become involved in any accident. Appreciate your sharing the ideas for your blog.

  21. Thanks for revealing your ideas with this blog. Furthermore, a fairy tale regarding the financial institutions intentions while talking about property foreclosures is that the financial institution will not have my repayments. There is a certain quantity of time that the bank is going to take payments occasionally. If you are also deep in the hole, they’ll commonly require that you pay the actual payment in whole. However, that doesn’t mean that they will have any sort of repayments at all. If you and the loan company can find a way to work anything out, the particular foreclosure procedure may end. However, when you continue to pass up payments under the new plan, the home foreclosure process can just pick up exactly where it was left off.

  22. miayabi888表示:

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

  23. I can’t express how much I admire the effort the author has put into writing this outstanding piece of content. The clarity of the writing, the depth of analysis, and the wealth of information provided are simply astonishing. His zeal for the subject is evident, and it has definitely struck a chord with me. Thank you, author, for sharing your knowledge and enriching our lives with this incredible article!

  24. Arnoldten表示:

    medication from mexico pharmacy mexican pharmacy mexican online pharmacies prescription drugs

  25. semenx表示:

    I was curious if you ever considered changing the structure of your website? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or 2 images. Maybe you could space it out better?

  26. Hey very cool site!! Man .. Excellent .. Amazing .. I will bookmark your blog and take the feeds also?I am happy to find numerous useful information here in the post, we need work out more strategies in this regard, thanks for sharing. . . . . .

  27. A formidable share, I just given this onto a colleague who was doing slightly evaluation on this. And he in truth purchased me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to debate this, I really feel strongly about it and love studying extra on this topic. If attainable, as you develop into expertise, would you mind updating your weblog with more particulars? It is highly useful for me. Big thumb up for this blog post!

  28. VMware was one of the most stable stocks, as its fourth-quarter earnings rose by 67, as a result the shares surged 5 to $90.30 in after-hours trading.

  29. Nice post. I was checking continuously this blog and I’m impressed! Very useful information particularly the last part 🙂 I care for such information much. I was looking for this certain information for a very long time. Thank you and best of luck.

  30. I do accept as true with all of the ideas you have presented for your post. They are really convincing and can certainly work. Still, the posts are too short for beginners. Could you please extend them a bit from next time? Thanks for the post.

發佈留言

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