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

  1. Five years later, on 3 September 1849, two kids were baptised on the Third Road Presbyterian Church in Dayton, Ohio: William Henry Breene and Martha Jane Breene.

  2. And since it’s going to take a while to make buddies if you are new, it is good to have a pet proper off the bat.

  3. 7047 株価表示:

    Rain meant no work and more sleep.

  4. Certainly, I properly remember, in the St Patrick’s Days of my American youth, feeling unsure as to whether my family history gave me ‘real’ Irish heritage, or not – the Scots-Irish, i.e.

  5. These kinds of insurance plans are designed to pay advantages along with your common insurance coverage plan.

  6. They’re both fashionable strolling shoes that are good for walking all day.

  7. FlyBondi and Jetsmart are two funds airways with dirt-low cost prices (but expect to pay for each add-on like luggage).

  8. Even when sporting them on heat, humid days, we stayed comfortably dry and averted blisters and chafing.

  9. The lighting is coming from directly above so the highlights go on the top pixels of the form.

  10. Hey there! Do you use Twitter? I’d like to follow you if that would be ok. I’m definitely enjoying your blog and look forward to new posts.

  11. He became deeply involved in the life of the Forest Avenue Presbyterian Church, the Loyal Legion (a Union Military veterans’ organisation), and other civic teams.

  12. Pantry furnishings could be helpful when you should not have a stroll in pantry, or if the cupboard space you may have isn’t just quite large enough to retailer your whole cooking objects.

  13. 3963 株価表示:

    The soles are comfortable but supportive for lengthy sightseeing days strolling and standing.

  14. A construction mission is often a industrial endeavor.

  15. The soiled souls peopling Tom Waits’ songs have theirs tattooed on their arms.

  16. They’re good if a person juices once in a while.

  17. As a result of it’s time to find a job, witches, and hopefully, as you start this grueling quest, you’ll keep in mind one very important thing: Setting an intention have to be adopted by way of with decisive action.

  18. When can I find the perfect offers on UGG boots?

  19. Make sure and invest a touch of power with the very best strolling cane for stability in your grasp to make sure that the canes handle a stable match.

  20. 俳句 て表示:

    With time to spare, we spent the morning perusing the retailers across the airport; not precisely the total Japanese expertise, however still an enchanting start to it.

  21. The situation also plays an integral part in figuring out worth.

  22. For a extra in-depth look at the ideas Darwin was hatching, learn How Pure Choice Works and how Evolution Works.

  23. Their French shoe brands have a distinctive style that exudes feminity combined with chic, luxurious, and comfort at affordable prices.

  24. There are lots of dealers in wholesale house decor equipment.

  25. UGG boots for women have been the company’s iconic product for years.

  26. All Canadians are allowed to enter Argentina via all ports of entry, together with sea, land, and air.

  27. In the aftermath and panic of strolling away from a job that paid my bills and gave me some semblance of a normal individual, I decided to make use of this newfound time to re-join with my longtime love of bubbling cauldrons, flickering candles and the occult in an effort to revive balance in my life and heal my mental well being.

  28. Selecting a Demon Slayer PFP is a personal alternative that reflects which features of the collection you join with most deeply.

  29. Asiatic stays just like those found at Inform el-Daba have been discovered there and attributed to the Hyksos (Holladay 1992b: 588-89; 1997:332-34).

  30. Normanfer表示:

    farmacia online barata y fiable: farmacia online envio gratis valencia – farmacia barata

發佈留言

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