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

  1. The launch in Australia is the first for C-Swap in the Southern hemisphere and the platform is designed to be adaptable to the changing requirements driven by regulatory reform in the Asian markets.

  2. DanielTet表示:

    order cytotec online https://lipitor.guru/# buying lipitor online
    lasix generic

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

  4. Mazrifb表示:

    Привет, друзья!
    Официальная покупка диплома вуза с сокращенной программой в Москве
    cryptocoinsnewshub.com

  5. Dino Game 129表示:

    This is without a doubt one of the finest articles I’ve read on this topic! The author’s comprehensive knowledge and zeal for the subject are apparent in every paragraph. I’m so appreciative for coming across this piece as it has enriched my comprehension and stimulated my curiosity even further. Thank you, author, for investing the time to craft such a remarkable article!

  6. DanielTet表示:

    Misoprostol 200 mg buy online https://tamoxifen.bid/# how to get nolvadex
    lasix tablet

  7. A day trader can close out their positions before the end of the day and not be subject to overnight margin requirements.however, those with positions are now subject to exchange margin requirements.

  8. To additional assist you find out about the markets, sign in for a free exchange game to induce started within the markets innocuous, below.

  9. Also visit my blog post … highstakes login

  10. You can also gather ideas by visiting the many websites that offer bath design products or by spending some time “just looking” in the local bath design center or department of your nearby home improvement store.

  11. Personal sellers should also be mindful of any suspicious pursuits and learn more on the topic of this Act in relation to the selling of their own property.

  12. The position place at the Forex market in such way is refer to as covered because the investor owns the share or the currency pair and the right to deliver the pair on the call option, which he has sold and as it is exercised by the option holder.

  13. Dino Game 127表示:

    Thank you for another informative site. Where else could I get that type of info written in such a perfect way? I’ve a project that I am just now working on, and I’ve been on the look out for such information.

  14. Additionally, strategies to promote collaboration and integration between PMHNPs, primary care providers, and other mental health professionals should be developed.

  15. If you are a market participant there is one a blaring truth in all of this.

  16. Dino Game 129表示:

    Nice post. I be taught something more difficult on completely different blogs everyday. It would all the time be stimulating to read content material from different writers and apply somewhat one thing from their store. I?d prefer to use some with the content on my weblog whether or not you don?t mind. Natually I?ll provide you with a link in your web blog. Thanks for sharing.

  17. Dino Game 120表示:

    After examine a number of of the blog posts on your website now, and I really like your approach of blogging. I bookmarked it to my bookmark web site listing and shall be checking again soon. Pls check out my web page as nicely and let me know what you think.

  18. Yrefgdl表示:

    Привет, друзья!
    Приобрести диплом любого университета.
    cookownfood.blogspot.com/2012/11/cold-bean-thread-noodles-with-spinach

  19. Jamesric表示:

    buy generic lipitor: cheapest ace inhibitor – lipitor generic brand

  20. Undeniably believe that that you said. Your favourite justification seemed to be at the net the simplest thing to be aware of. I say to you, I definitely get irked at the same time as people consider concerns that they just don’t know about. You managed to hit the nail upon the top as smartly as defined out the entire thing with no need side-effects , other people could take a signal. Will likely be again to get more. Thank you

  21. Jamesric表示:

    lipitor 10 mg cost: buy atorvastatin online – lipitor online

  22. Jamesric表示:

    lasix 40mg: furosemide online – lasix generic

  23. Dino Game 127表示:

    I’m not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come back later. Cheers

  24. Dino Game 125表示:

    Thank you for some other fantastic article. Where else may anybody get that kind of information in such a perfect manner of writing? I have a presentation next week, and I’m at the look for such info.

  25. Great post however , I was wondering if you could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit further. Thank you!

  26. I have noticed that credit score improvement activity should be conducted with techniques. If not, you might find yourself causing harm to your position. In order to reach your goals in fixing your credit rating you have to verify that from this minute you pay your complete monthly fees promptly in advance of their booked date. It is significant simply because by certainly not accomplishing that, all other activities that you will choose to adopt to improve your credit rank will not be helpful. Thanks for sharing your thoughts.

  27. Dino Game 118表示:

    Via my observation, shopping for electronics online may be easily expensive, but there are some tips and tricks that you can use to obtain the best bargains. There are continually ways to uncover discount deals that could make one to hold the best electronic products products at the smallest prices. Good blog post.

  28. One thing I’d really like to reply to is that weightloss system fast may be possible by the suitable diet and exercise. People’s size not only affects appearance, but also the complete quality of life. Self-esteem, depression, health risks, along with physical abilities are affected in fat gain. It is possible to make everything right and still gain. In such a circumstance, a problem may be the root cause. While an excessive amount food but not enough work out are usually at fault, common health conditions and popular prescriptions can greatly increase size. Thanks for your post in this article.

發佈留言

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