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

20,492 Responses

  1. 山陽とは表示:

    If one of many computer systems has a printer hooked up, then the opposite laptop can print to it over the network.

  2. Nevertheless, needless to say there could also be time-sensitive necessities, resembling buying within a certain number of days after booking your journey or earlier than a sure date.

  3. The asset liquidity situation arose from LTCM’s failure to account for liquidity turning into extra worthwhile, as it did following the crisis.

  4. The Journal of Modern African Research.

  5. In distinction, his father Benjamin was, in later life, one of the outstanding of the Patriot leaders of the American Revolution and a Founding Father of the United States.

  6. Fortunately, there are lots of good substitutes if you’re in the midst of cooking and your recipe requires white wine, and also you understand you drank it all!

  7. Once you personal a home, you’ll be able to all the time save up for renovations.

  8. Haukkanen, Pentti; Merikoski, Jorma Okay.; Tossavainen, Timo (2020).

  9. An organization Secretary is a legal advisor to any firm, and holds excessive worth.

  10. You just should be sure that the lodging of your alternative fits your every need as a traveller so that your vacation can be a memorable one, irrespective of how brief.

  11. Lepic, Bojan (April 1, 2021).

  12. Nevertheless, HDFC Mutual Fund later recovered all the investment made within the non-convertible debentures issued by Essel Group corporations.

  13. The estimated impact is given as a mean for the completely different revenue ranges.

  14. The Valdez spill would grow to be a case examine in how operator fatigue, environmental elements and faulty decision-making can combine for disastrous results.

  15. I used to be approached by a company producing Ugg-like boots to assessment their boots, get a free pair in the process, and get a great deal for my readers.

  16. Loan modification attorneys generally is a trusted ally in the battle to maintain your house.

  17. Within the early years, when Ryanair had a total of 450 workers who each had shares in the company, there was an agreement that staff would not be a part of a labour union on the basis that they’d affect how the company was run.

  18. DanielAbice表示:

    http://amoxstar.com/# azithromycin amoxicillin

  19. I can’t express how much I admire the effort the author has put into writing this exceptional piece of content. The clarity of the writing, the depth of analysis, and the wealth of information offered are simply remarkable. Her enthusiasm for the subject is evident, and it has undoubtedly made an impact with me. Thank you, author, for offering your knowledge and enlightening our lives with this exceptional article!

  20. Thanks for your handy post. In recent times, I have come to be able to understand that the symptoms of mesothelioma are caused by the build up connected fluid between the lining on the lung and the upper body cavity. The sickness may start inside chest vicinity and propagate to other body parts. Other symptoms of pleural mesothelioma include weight reduction, severe deep breathing trouble, throwing up, difficulty taking in food, and swelling of the neck and face areas. It should be noted that some people existing with the disease do not experience virtually any serious signs at all.

  21. Completely sealing crawlspace vents can lead to moisture problems, akin to mold and wood rot, attributable to insufficient ventilation.

  22. Some corporations encourage employees to buy their inventory and may even give the 401(okay) matching amount in company inventory moderately than money.

  23. It will possibly both be hardwired right into a car’s electrical system or provided with an inside battery that lasts about 5 years.

  24. OMT operations end as soon as “their aims are achieved” or when there is non-compliance with the macroeconomic adjustment or precautionary programme.

  25. She ultimately fulfilled this command by slaying a clone of Luke referred to as Luuke Skywalker, whom Palpatine had made in an try to make use of him against the unique, although this plot ultimately would fail because of Mara’s fatal attack on the clone.

  26. A young entrepreneur starting her personal enterprise, for instance, might need a perfectly completely happy marriage.

  27. Permit us to sneak fast peruse Inventory suggestions and commercialism suggestions.

  28. Quick-run predictions indicate that given modifications in futures costs can only a temporary (one time) change in spot costs.

  29. I have said earlier than and I will say once more that Westerners usually are not in contact with the Arab mindset.

發佈留言

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