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

  1. RobertMef表示:

    indian pharmacies safe: indianpharmacy com – buy prescription drugs from india

  2. MauriceGueda表示:

    best india pharmacy: india pharmacy mail order – india online pharmacy

  3. Josephfub表示:

    indian pharmacy indian pharmacy best online pharmacy india

  4. MauriceGueda表示:

    india pharmacy mail order: indian pharmacy paypal – india pharmacy mail order

  5. Josephfub表示:

    best online pharmacy india Online medicine order best india pharmacy

  6. With almost everything which seems to be developing throughout this particular subject material, many of your perspectives happen to be relatively exciting. However, I appologize, because I do not subscribe to your whole suggestion, all be it radical none the less. It seems to me that your remarks are actually not totally validated and in simple fact you are generally your self not really entirely certain of the argument. In any case I did take pleasure in looking at it.

  7. MauriceGueda表示:

    indian pharmacy online shopping: why is zyrtec d behind the pharmacy counter – skip’s pharmacy naltrexone

  8. Josephfub表示:

    rx clinic pharmacy charlotte nc bangkok pharmacy kamagra isotretinoin indian pharmacy

  9. RobertMef表示:

    purple pharmacy mexico price list: mexico pharmacies prescription drugs – reputable mexican pharmacies online

  10. Together with everything which seems to be building throughout this specific area, your points of view tend to be quite stimulating. Having said that, I am sorry, but I do not subscribe to your entire suggestion, all be it radical none the less. It appears to everyone that your opinions are actually not completely validated and in reality you are generally yourself not completely convinced of your assertion. In any case I did appreciate reading it.

  11. Greetings! I know this is kind of 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 difficulty finding one? Thanks a lot!

  12. After research a number of of the blog posts on your web site now, and I really like your manner of blogging. I bookmarked it to my bookmark website checklist and can be checking back soon. Pls take a look at my web site as effectively and let me know what you think.

  13. ArthurKib表示:

    https://mexicopharmacy.cheap/# mexico pharmacies prescription drugs

  14. ArthurKib表示:

    https://indianpharmacy.company/# п»їlegitimate online pharmacies india

  15. Great blog post. A few things i would like to bring about is that laptop or computer memory should be purchased should your computer still can’t cope with whatever you do by using it. One can mount two good old ram boards of 1GB each, as an example, but not certainly one of 1GB and one having 2GB. One should make sure the manufacturer’s documentation for the PC to make certain what type of ram it can take.

  16. It’s a shame you don’t have a donate button! I’d most certainly donate to this excellent blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to brand new updates and will talk about this blog with my Facebook group. Chat soon!

  17. RobertMef表示:

    buying from online mexican pharmacy: buying from online mexican pharmacy – purple pharmacy mexico price list

  18. I am no longer positive the place you are getting your info, however good topic. I must spend some time studying much more or understanding more. Thanks for magnificent info I used to be on the lookout for this info for my mission.

  19. Thanks for your tips about this blog. Just one thing I would want to say is purchasing consumer electronics items in the Internet is nothing new. In truth, in the past several years alone, the market for online electronic devices has grown significantly. Today, you will discover practically almost any electronic device and gizmo on the Internet, including cameras along with camcorders to computer spare parts and games consoles.

  20. I’m extremely inspired along with your writing talents as neatly as with the layout in your weblog. Is this a paid subject matter or did you modify it your self? Anyway stay up the nice quality writing, it?s rare to see a great weblog like this one these days..

  21. bokep jilbab表示:

    I haven?t checked in here for a while because I thought it was getting boring, but the last few posts are good quality so I guess I will add you back to my everyday bloglist. You deserve it my friend 🙂

  22. pure cbd oil表示:

    It?s really a nice and helpful piece of information. I?m glad that you shared this helpful info with us. Please keep us informed like this. Thanks for sharing.

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

  24. Hey there I am so excited I found your webpage, I really found you by error, while I was looking on Google for something else, Anyhow I am here now and would just like to say thanks a lot for a fantastic post and a all round enjoyable blog (I also love the theme/design), I don’t have time to read through it all at the minute but I have saved it and also added in your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the superb work.

  25. This really answered my downside, thanks!

  26. Hey very nice site!! Guy .. Beautiful .. Amazing .. I will bookmark your website and take the feeds additionally?I am glad to find a lot of useful info here within the post, we want work out more techniques in this regard, thanks for sharing. . . . . .

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

  28. Wow, wonderful blog layout! How lengthy have you been blogging for? you made running a blog look easy. The whole glance of your site is great, as neatly as the content material!

  29. ArthurKib表示:

    https://indianpharmacy.company/# best india pharmacy

發佈留言

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