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

35,117 Responses

  1. JAVHD表示:

    Hey there! This post could not be written any better! Reading through this post reminds me of my previous room mate! He always kept chatting about this. I will forward this page to him. Fairly certain he will have a good read. Thank you for sharing!

  2. JAVHD表示:

    Howdy just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different web browsers and both show the same outcome.

  3. Yjnbah表示:

    purchase coumadin online – order reglan for sale cozaar 50mg sale

  4. Dwightkak表示:

    canadian discount pharmacy: usa canada pharm – canada drugs online review

  5. JAVHD表示:

    Thank you for sharing excellent informations. Your site is so cool. I am impressed by the details that you have on this site. It reveals how nicely you understand this subject. Bookmarked this website page, will come back for extra articles. You, my pal, ROCK! I found just the info I already searched all over the place and just could not come across. What a perfect website.

  6. Albertbiave表示:

    https://usacanadapharm.shop/# www canadianonlinepharmacy

  7. JAVHD表示:

    Thank you for sharing excellent informations. Your website is very cool. I’m impressed by the details that you?ve on this web site. It reveals how nicely you perceive this subject. Bookmarked this website page, will come back for more articles. You, my friend, ROCK! I found simply the information I already searched all over the place and simply could not come across. What a perfect web-site.

  8. JAVHD表示:

    Oh my goodness! I’m in awe of the author’s writing skills and talent to convey complex concepts in a clear and concise manner. This article is a real treasure that deserves all the applause it can get. Thank you so much, author, for offering your wisdom and giving us with such a valuable treasure. I’m truly appreciative!

  9. EverettTuh表示:

    global pharmacy canada http://usacanadapharm.com/# usa canada pharm
    canadian pharmacy victoza

  10. JAVHD表示:

    You could certainly see your expertise within the paintings you write. The sector hopes for more passionate writers such as you who are not afraid to say how they believe. All the time go after your heart.

  11. JAVHD表示:

    One more thing. It’s my opinion that there are a lot of travel insurance websites of dependable companies that allow you enter your vacation details and acquire you the quotations. You can also purchase the international travel cover policy on-line by using the credit card. All you have to do should be to enter all travel particulars and you can begin to see the plans side-by-side. You only need to find the system that suits your capacity to pay and needs and then use your credit card to buy the idea. Travel insurance online is a good way to check for a dependable company with regard to international travel insurance. Thanks for revealing your ideas.

  12. StephenCer表示:

    canada drug pharmacy: canada pharmacy online legit – USACanadaPharm

  13. JAVHD表示:

    F*ckin? awesome things here. I?m very glad to see your article. Thanks a lot and i am looking forward to contact you. Will you please drop me a e-mail?

  14. Albertbiave表示:

    https://usacanadapharm.com/# usa canada pharm

  15. StephenCer表示:

    77 canadian pharmacy: canadian pharmacy mall – canadian pharmacy

  16. JAVHD表示:

    Good article. It is quite unfortunate that over the last 10 years, the travel industry has had to fight terrorism, SARS, tsunamis, bird flu, swine flu, and also the first ever entire global tough economy. Through everthing the industry has really proven to be powerful, resilient in addition to dynamic, getting new solutions to deal with trouble. There are constantly fresh complications and opportunity to which the field must once again adapt and react.

  17. JAVHD表示:

    hello!,I like your writing so so much! proportion we be in contact more about your article on AOL? I require an expert in this area to solve my problem. Maybe that is you! Having a look forward to see you.

  18. TimothyDok表示:

    best online canadian pharmacy usa canada pharm usa canada pharm

  19. EverettTuh表示:

    canadian pharmacy drugs online https://usacanadapharm.com/# canadian valley pharmacy
    canadian pharmacy scam

  20. Dwightkak表示:

    canadian pharmacy near me: USACanadaPharm – USACanadaPharm

  21. f168表示:

    Itís hard to come by educated people on this topic, however, you seem like you know what youíre talking about! Thanks

  22. Dwightkak表示:

    USACanadaPharm: USACanadaPharm – USACanadaPharm

  23. JamesBlate表示:

    Официальный TG канал проекта – 7k casinо, теперь в вашем Telegram! Актуальное зеркало, ссылки на вход, промокоды на фриспины, регистрация. слоты, играй на реальные деньги с нами! Сайт 7к казинo
    https://vk.com/slot7kofficial

  24. Dwightkak表示:

    usa canada pharm: trusted canadian pharmacy – USACanadaPharm

  25. Albertbiave表示:

    https://usacanadapharm.shop/# my canadian pharmacy reviews

  26. EverettTuh表示:

    adderall canadian pharmacy https://usacanadapharm.shop/# usa canada pharm
    canadian drug stores

  27. StephenCer表示:

    maple leaf pharmacy in canada: usa canada pharm – USACanadaPharm

  28. Dwightkak表示:

    USACanadaPharm: canadian pharmacy meds reviews – USACanadaPharm

  29. Albertbiave表示:

    https://usacanadapharm.shop/# usa canada pharm

  30. EverettTuh表示:

    canada pharmacy 24h http://usacanadapharm.com/# safe canadian pharmacy
    canadianpharmacy com

發佈留言

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