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

15,536 Responses

  1. With this “one-sidedness” thought, Michelangelo created considered one of Rome’s most majestic spectacles.

  2. Also referred to as minimalist sneakers they are meant to reduce injuries reminiscent of tendinitis.

  3. CharlesrooNo表示:

    Farmacia online piГ№ conveniente Farmacie online sicure farmacie online sicure

  4. best ro表示:

    I have really noticed that repairing credit activity must be conducted with techniques. If not, chances are you’ll find yourself destroying your ranking. In order to succeed in fixing your credit score you have to always make sure that from this second you pay your monthly dues promptly before their scheduled date. It is really significant for the reason that by never accomplishing so, all other measures that you will choose to adopt to improve your credit rank will not be successful. Thanks for sharing your ideas.

  5. Intensive Outpatient Therapy for Arizona Residents Our intensive outpatient therapy program helps clients set clear, definable milestones in overcoming their addiction.

  6. top server ro表示:

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

  7. Family legend has it that when it became clear that the Civil Warfare was imminent, younger Joseph, who was not solely underage but in addition moderately small in stature – his comrades would later name him “the Little Captain” – attempted to observe his older brother into the Union military, solely to be informed to go away.

  8. Do you like traveling?

  9. CharlesrooNo表示:

    acquistare farmaci senza ricetta Cialis generico controindicazioni Farmacie online sicure

  10. Often, the whole amount of co-insurance coverage it’s important to pay in a given policy is capped by the coverage’s maximum.

  11. If you learn this article from the beginning, you already know what the job situation is like internationally now.

  12. Crafted from gentle, full-grain leather, the shoes mold to your ft as you wear them, with anatomically contoured footbeds that we found immediately comfy-no breaking-in required.

  13. Employers can tout an FSA as a fantastic benefit in an effort to draw and keep workers, while both employer and worker can save cash on payroll and social security taxes.

  14. What would success look wish to you?

  15. And Obama’s vitality agenda could possibly be even more damaging if he, yet again, shrugs off TransCanada’s Keystone XL oil pipeline, which would generate tens of hundreds of jobs whereas lowering Americans’ energy dependence on corrupt Middle Japanese regimes.

  16. Requirements for conveyors define volume of goods, most load capacity and the velocity and movement of products.

  17. Suavs Ladies’s The Zilker Gum: Though comfortable, we had issues about the lengthy-term durability of those shoes.

  18. What’s one of the best moment to solid these job spells?

  19. Who spreads the rumor about Geum Jan-di’s so-referred to as pregnancy?

  20. They never exit on a double date.

  21. 360: Several years in the past, you and i spoke about the problem of ocean acidification, which has always been a kind of stepbrother of global warming, though by some accounts equally critical.

  22. Please let me know if you’re looking for a author for your weblog. You have some really good articles and I believe I would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some material for your blog in exchange for a link back to mine. Please send me an e-mail if interested. Thanks!

  23. The great thing about the scene is sort of indescribable — what can one say about a scene that should be one of many pure wonders of the world?

  24. Good day! Would you mind if I share your blog with my twitter group? There’s a lot of people that I think would really appreciate your content. Please let me know. Cheers

  25. If the floe broke up there would be no extra waiting and suffering.

  26. Pullao is my family’s most beloved dish, handed down from pre-Partition India, however Chandni’s Punjabi model was spicy and a bit sour, not like the aromatic brothiness of the Panipati pullao that I used to be used to.

  27. Moderators are usually not staff or representatives of HWZ.

  28. EdwardMet表示:

    comprare farmaci online all’estero Farmacie on line spedizione gratuita Farmacie online sicure

  29. Purchase rules for gun sales in contiguous states repealed, now that nationwide guidelines are in place.

  30. Hello There. I discovered your weblog using msn. This is a really well written article. I?ll make sure to bookmark it and come back to read extra of your helpful information. Thank you for the post. I?ll certainly return.

發佈留言

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