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

17,177 Responses

  1. Diplomi_faot表示:

    купить диплом о высшем образовании томск купить диплом о высшем образовании томск .

  2. Artwork Deco inside, two balconies and a magnificent domed ceiling.

  3. Nevertheless, its high melting temperature (1723 °C) and viscosity make it tough to work with.

  4. Fashionable works of glass art will be seen in dedicated glass museums and museums of contemporary artwork.

  5. Embrace on traces 22a, 23a, 24a, 25a, 29a, 29b, and 29c any labor costs correctly allocable to the onsite preparation, assembly, or authentic set up of the property.

  6. Regardless of going into UEFA Euro 2016 as an understudy to former Arsenal teammate Wojciech Szczęsny, an injury in the primary game of the tournament towards Northern Eire led to Fabiański turning into first selection for the rest of the tournament..

  7. Fabiański received criticism for conceding delicate objectives within the Porto match as he scored an personal aim and was blamed for the second purpose after picking up a backpass from Sol Campbell, with Porto scoring from the resulting free-kick.

  8. Picture in gallery beneath depicts the Coat of Arms of the Douglas Clan and is shown courtesy Jean Maskell.

  9. 76. Two younger ladies converse in a formal drawing room; one in a layered gown with a floral trim; the other in a green striped costume.

  10. This condition is named submit herpetic neuralgia.

  11. The drawback is that your services or products must fall exactly inside the main target for the present, or you will not get the outcomes you need.

  12. But as a dish unto itself, risotto comes from Northern Italy the place they cook it creamy and combined with cheese, butter and spices.

  13. Derekfar表示:

    slot oyunlar?: slot oyunlar? – az parayla cok kazandiran slot oyunlar?

  14. Kobel changed Omlin after Switzerland’s first match.

  15. Remember, you may need to think about costs for upkeep, repairs, and ribbons.

  16. Diplomi_mhpi表示:

    куплю диплом получать prem-diplom77.ru .

  17. For a more conventional method to this philosophy, see the intriguing archaeological model of the bathroom on the next page.

  18. To make sure optimum performance and longevity of your electric typewriter, regular upkeep is important.

  19. See the following section to discover the inventive fusion of several different styles.

  20. The heat pump is often put in because the final merchandise within the water stream before the water returns to the pool, ie after the filter.

  21. Ahead of the 2008 season, it was announced that Kawashima can be appointed as Kawasaki Frontale’s vice-captain and stayed to stay as the club’s first alternative goalkeeper.

  22. Отличный сайт! Всем рекомендую!шкафы на заказ

  23. 株価 jp表示:

    For armholes, measure down eight inches from the top of the box on each sides.

  24. We need to raise nations as much as our level.

  25. Whether or not featuring characters, symbols, or patterns, anime-themed curtains can significantly change the feel and appear of your room, merging functionality with fan artwork.

  26. I am curious to find out what blog platform you’re working with? I’m experiencing some minor security issues with my latest blog and I would like to find something more safe. Do you have any suggestions?

  27. Word: She labored with Lowndes and Drury / Glass Home.

  28. Typically, show literature will list solely the numbers and normal titles of their attendees.

發佈留言

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