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

  1. In the semi-finals towards Colombia, he scored Switzerland’s last goal of their 4-zero win to reach their first ultimate of a FIFA competition since a 3-0 loss to Uruguay within the 1924 Olympics.

  2. We were utilizing a giant grinder blade and that despatched a flame right off the facet of my face and in my ears.

  3. WalesOnline. Clarke, Adrian (13 October 2018).

  4. I think that is one of the such a lot significant information for me. And i am happy reading your article. But should commentary on some basic issues, The website style is perfect, the articles is in point of fact nice : D. Excellent activity, cheers

  5. Pugin first had contact with the John Hardmans throughout the development of St Chad’s Chapel, the forerunner to the cathedral scheme.

  6. This only lasts for a millisecond or so while the compressor starts and the current then reverts to the conventional running present for the unit.

  7. They’re intently related to Artwork Nouveau.

  8. They’d two sons and two daughters, Edith, Dominick, Lucy, and John.

  9. The approach of making stained glass home windows in the early Gothic was essentially the identical as within the Romanesque period.

  10. LarryCoell表示:

    Canl? Casino Siteleri casino siteleri win Casino Siteleri

  11. Sportstar, Workforce (9 July 2019).

  12. Povey Brothers Studio, also known as Povey Brothers Artwork Glass Works or Povey Bros.

  13. Somebody finally received it right but I bet that they had more than just a few arguments with their builder.

  14. Like other windows of the period, much of the window is grisaille, permitting in a most of gentle, whereas the figures are framed by elaborate architectural detail, matching the ornate architecture of the church itself.

  15. The more particular you will get, the extra possible they may remember who you might be once you call.

  16. Overlap some objects and have others pouring out of sides and entrance.

  17. Eleven August: The opening day of the season sees young striker Nicky Maynard fracture his fibula.

  18. Sure kitchen color groups — for instance, black, purple, and white — are paying homage to the cozy intimacy of roadside diners.

  19. Hills, Ann (April 1987).

  20. Celebrating French-Canadian history in a really on-brand winter wonderland-y means.

  21. adult webcams表示:

    Hmm is anyone else encountering problems with the images on this blog loading? I’m trying to find out if its a problem on my end or if it’s the blog. Any responses would be greatly appreciated.

  22. My Rating: Romance one zero one is a witty romcom webtoon good for readers in their 20s.

  23. A more energizing modern approach, however, shifts these basic-trying rooms to a lighter palette.

  24. In September 2019, he suffered a hip damage.

  25. Sa-Eun can generally say something that units off Jin-Soo’s anger, which causes Jin-Soo to beat up Sa-Eun.

  26. General, I’ll give this isekai webtoon an 8/10.

  27. The clothes of the figures is often of the darker shades, royal blue, wine crimson and darkish inexperienced and is lined or bordered with intricately decorated yellow-stained glass.

  28. Your possibilities of getting meals poisoning from an apple are slim, however not zero, so it is essential to clean your apples before you chow down as properly.

  29. 保険 南海表示:

    If you want to make a statement, a custom-designed area rug that echoes the room’s colours can be the icing on the cake.

發佈留言

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