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...

38,087 Responses

  1. Hey! Would you mind if I share your blog with my myspace group? There’s a lot of people that I think would really enjoy your content. Please let me know. Thanks

  2. Jasonzitte表示:

    Their loyalty program offers great deals.
    how can i get generic cytotec online
    I’ve sourced rare medications thanks to their global network.

  3. Once I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the same comment. Is there any manner you can remove me from that service? Thanks!

  4. Here too, a walkway will provide the answer.

  5. Victorprima表示:

    They offer international health solutions without borders.
    how to buy cheap clomid without rx
    They’re globally connected, ensuring the best patient care.

  6. 1win_jkMl表示:

    1win бонус за приложение http://1win13.am/ .

  7. Hello there, just become aware of your blog thru Google, and located that it is really informative. I?m gonna watch out for brussels. I will appreciate in case you proceed this in future. Many other folks shall be benefited from your writing. Cheers!

  8. WalterCherm表示:

    A trusted partner for patients worldwide.
    https://lisinoprilpharm24.top/
    Quick service without compromising on quality.

  9. I like what you guys are up also. Such intelligent work and reporting! Carry on the superb works guys I?ve incorporated you guys to my blogroll. I think it will improve the value of my website 🙂

  10. I’m curious to find out what blog system you are utilizing? I’m having some small security issues with my latest website and I’d like to find something more risk-free. Do you have any solutions?

  11. WalterCherm表示:

    Their worldwide pharmacists’ consultations are invaluable.
    https://cytotecpharm24.top/
    Delivering worldwide standards with every prescription.

  12. DavidFus表示:

    Все о недвижимости https://9312886940.ru покупка, аренда, ипотека. Разбираем рыночные тренды, юридические тонкости, лайфхаки для выгодных сделок. Помогаем выбрать квартиру, рассчитать ипотеку, проверить документы и избежать ошибок при сделках с жильем. Актуальные статьи для покупателей, арендаторов и инвесторов.

  13. In accordance with my research, after a foreclosures home is available at a sale, it is common to the borrower to still have some sort ofthat remaining unpaid debt on the bank loan. There are many creditors who make an effort to have all rates and liens paid back by the next buyer. On the other hand, depending on specific programs, polices, and state guidelines there may be a few loans that are not easily solved through the transfer of lending products. Therefore, the duty still lies on the lender that has obtained his or her property in foreclosure process. Many thanks for sharing your opinions on this blog.

  14. One thing is always that one of the most prevalent incentives for using your credit cards is a cash-back or perhaps rebate provision. Generally, you’ll get 1-5 back for various purchases. Depending on the credit card, you may get 1 back on most buying, and 5 back on buying made on convenience stores, filling stations, grocery stores along with ‘member merchants’.

  15. It is my belief that mesothelioma can be the most fatal cancer. It contains unusual qualities. The more I look at it a lot more I am sure it does not work like a true solid human cancer. In the event that mesothelioma is actually a rogue viral infection, hence there is the probability of developing a vaccine and offering vaccination to asbestos open people who are really at high risk involving developing long run asbestos relevant malignancies. Thanks for revealing your ideas on this important health issue.

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

  17. Victorprima表示:

    Professional, courteous, and attentive – every time.
    gabapentin stroke risk
    The most trustworthy pharmacy in the region.

  18. I do like the manner in which you have framed this particular concern and it does indeed offer me a lot of fodder for thought. Nonetheless, because of just what I have observed, I simply trust as the remarks stack on that individuals stay on point and don’t embark upon a soap box regarding some other news du jour. All the same, thank you for this fantastic piece and though I do not concur with the idea in totality, I respect your point of view.

  19. Hello there, You have performed an incredible job. I will certainly digg it and in my opinion suggest to my friends. I am sure they will be benefited from this web site.

  20. Jasonzitte表示:

    Always greeted with warmth and professionalism.
    can i order generic cipro for sale
    The staff always goes the extra mile for their customers.

  21. Victorprima表示:

    A gem in our community.
    lisinopril medication generic names
    What side effects can this medication cause?

  22. Somebody essentially help to make seriously articles I would state. This is the first time I frequented your web page and thus far? I surprised with the research you made to create this particular publish incredible. Magnificent job!

  23. Jasonzitte表示:

    They understand the intricacies of international drug regulations.
    buying cheap clomid for sale
    Their international health campaigns are revolutionary.

  24. Victorprima表示:

    Bridging continents with their top-notch service.
    where can i get cipro pill
    A pharmacy that truly understands customer service.

  25. Please let me know if you’re looking for a article author for your weblog. You have some really great posts and I think I would be a good asset. If you ever want to take some of the load off, I’d really like to write some material for your blog in exchange for a link back to mine. Please blast me an e-mail if interested. Many thanks!

  26. WalterCherm表示:

    They consistently exceed global healthcare expectations.
    https://cytotecpharm24.top/
    Their vaccination services are quick and easy.

  27. WalterCherm表示:

    Actual trends of drug.
    https://gabapentinpharm24.top/
    Consistent service, irrespective of borders.

  28. 66lottery表示:

    Wonderful beat ! I would like to apprentice whilst you amend your site, how could i subscribe for a blog site? The account aided me a appropriate deal. I had been a little bit acquainted of this your broadcast offered shiny transparent idea

發佈回覆給「国家資格師と士」的留言 取消回覆

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