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

  1. 91 club app表示:

    Thanks for the suggestions about credit repair on your site. The thing I would offer as advice to people is always to give up the particular mentality they can buy currently and pay later. As being a society we tend to make this happen for many things. This includes getaways, furniture, along with items we wish. However, you’ll want to separate your current wants from the needs. While you’re working to raise your credit ranking score you really have to make some trade-offs. For example you possibly can shop online to save cash or you can turn to second hand suppliers instead of expensive department stores to get clothing.

  2. new platform表示:

    I am really loving the theme/design of your blog. Do you ever run into any browser compatibility issues? A number of my blog readers have complained about my site not working correctly in Explorer but looks great in Chrome. Do you have any ideas to help fix this problem?

  3. 91 login表示:

    Hello There. I found your blog using msn. This is a really well written article. I?ll make sure to bookmark it and return to read more of your useful info. Thanks for the post. I will certainly comeback.

  4. Thanks for your posting on the traveling industry. I’d also like to add that if your senior taking into consideration traveling, it’s absolutely crucial that you buy travel cover for retirees. When traveling, older persons are at biggest risk of experiencing a health care emergency. Buying the right insurance coverage package to your age group can protect your health and provide peace of mind.

  5. Ytrwko表示:

    order piracetam 800mg sale – buy sinemet 10mg online order sinemet 20mg pill

  6. Cassino com pagamentos rapidos Blaze

  7. Excellent read, I just passed this onto a colleague who was doing some research on that. And he just bought me lunch as I found it for him smile Therefore let me rephrase that: Thanks for lunch!

  8. Ganhe muito no melhor cassino Blaze

  9. Thanks for the advice on credit repair on your blog. The things i would advice people will be to give up a mentality that they can buy now and pay out later. As being a society most of us tend to do that for many issues. This includes vacation trips, furniture, and also items we wish. However, you’ll want to separate the wants out of the needs. As long as you’re working to raise your credit ranking score make some trade-offs. For example you possibly can shop online to save cash or you can visit second hand stores instead of expensive department stores to get clothing.

  10. Edwarddig表示:

    Pin Up Kazino ?Onlayn: Pin Up – Pin-up Giris

  11. Thanks for your write-up. Another issue is that being photographer involves not only problems in catching award-winning photographs but in addition hardships in acquiring the best photographic camera suited to your requirements and most especially problems in maintaining the grade of your camera. It is very accurate and visible for those photographers that are straight into capturing the nature’s exciting scenes – the mountains, the actual forests, the wild or maybe the seas. Going to these amazing places undoubtedly requires a dslr camera that can surpass the wild’s severe environments.

  12. Edwarddig表示:

    Pin Up: Pin-up Giris – Pin Up

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

  14. EarnestAvada表示:

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

    ks-elektronika.pl/product_ask_avaliable.php?products_id=71 
    http://www.nitrnd.com/blogs/43554/%D0%A1%D1%82%D0%B0%D0%BD%D1%8C%D1%82%D0%B5-%D0%BF%D1%80%D0%BE%D1%84%D0%B5%D1%81%D1%81%D0%B8%D0%BE%D0%BD%D0%B0%D0%BB%D0%BE%D0%BC-%D0%B7%D0%B0-%D0%BE%D0%B4%D0%BD%D1%83?lang=tr_tr 
    domstroy18.ru/chameleon 
    meqnas.co.za/posts/fsdfds 
    bestcoolfun.ru/page/32 

  15. cbd massage表示:

    I have seen that car insurance businesses know the motors which are liable to accidents and also other risks. In addition they know what types of cars are prone to higher risk as well as higher risk they may have the higher a premium charge. Understanding the straightforward basics connected with car insurance will assist you to choose the right sort of insurance policy that could take care of your family needs in case you get involved in an accident. Many thanks sharing the ideas on your blog.

  16. Simply desire to say your article is as astonishing. The clarity in your post is simply nice and i can assume you are an expert on this subject. Well with your permission allow me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please carry on the enjoyable work.

  17. RobertSax表示:

    https://autolux-azerbaijan.com/# Pin Up Azerbaycan ?Onlayn Kazino

  18. I have realized that over the course of constructing a relationship with real estate entrepreneurs, you’ll be able to come to understand that, in every single real estate exchange, a payment is paid. Ultimately, FSBO sellers never “save” the commission. Rather, they try to earn the commission by way of doing a strong agent’s occupation. In completing this task, they spend their money along with time to complete, as best they are able to, the jobs of an representative. Those responsibilities include uncovering the home via marketing, delivering the home to all buyers, creating a sense of buyer emergency in order to trigger an offer, scheduling home inspections, taking on qualification inspections with the mortgage lender, supervising repairs, and aiding the closing of the deal.

  19. Hi! This is my 1st comment here so I just wanted to give a quick shout out and tell you I truly enjoy reading your blog posts. Can you recommend any other blogs/websites/forums that cover the same subjects? Thanks a lot!

  20. cbd massage表示:

    I?ll immediately grab your rss as I can not find your e-mail subscription link or newsletter service. Do you’ve any? Please let me know in order that I could subscribe. Thanks.

  21. Thanks for your write-up. I would also like to opinion that the first thing you will need to carry out is find out if you really need credit improvement. To do that you need to get your hands on a replica of your credit history. That should really not be difficult, since the government necessitates that you are allowed to get one free copy of the credit report yearly. You just have to ask the right men and women. You can either find out from the website owned by the Federal Trade Commission and also contact one of the main credit agencies directly.

  22. Together with almost everything which appears to be building throughout this particular subject matter, your opinions tend to be quite refreshing. Nevertheless, I appologize, because I can not give credence to your entire idea, all be it stimulating none the less. It appears to everybody that your opinions are actually not totally rationalized and in simple fact you are generally your self not thoroughly certain of your assertion. In any event I did enjoy looking at it.

發佈留言

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