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

  1. By clearing the underground dungeon, you’ll have the ability to make your approach again up top to the Forest Fortress.

  2. zentai表示:

    I am not positive where you’re getting your info, however good topic. I needs to spend some time learning more or understanding more. Thanks for fantastic info I used to be looking for this information for my mission.

  3. To perform this, overhangs on home windows, which are a primary means of daylighting, must be sized to forestall direct gentle (mild that is in direct line to the sun) from coming into besides, the place desired, in the heating season.

  4. hi!,I love your writing very much! share we keep up a correspondence more about your article on AOL? I require a specialist on this house to resolve my problem. Maybe that’s you! Looking ahead to see you.

  5. Sergiohex表示:

    https://rybelsus.tech/# semaglutide

  6. Sergiohex表示:

    https://prednisolone.pro/# buy prednisone 10mg online

  7. Every so often a greenish wave of the Northern Lights would roll throughout the hollow of the excessive heavens, flick like a flag, and disappear; or a meteor would crackle from darkness to darkness, trailing a shower of sparks behind.

  8. What the Church needs is real, biblical transformation; tragically, what many churches and leaders are selling is conformity to the pattern and mold of the business world.

  9. It’s specialized and actually hard.

  10. After totally testing the Allbirds Tree Runners on our toes and in the lab, we got here to the conclusion that it’s probably the most snug walking shoe for travel.

  11. 込 書き順表示:

    There are various obtainable firms that offer the same prices for differing types of meal and typically it is cheaper.

  12. zentai表示:

    Heya i am for the primary time here. I found this board and I find It truly helpful & it helped me out a lot. I hope to give one thing again and help others like you aided me.

  13. You are writing your personal destiny as you read this.

  14. It’s finest to spot clear your travel shoes on the go slightly than waiting for dirt and stains to set in, since they are often more durable to remove the longer you wait.

  15. AlfredHag表示:

    buy neurontin 100 mg neurontin 800 mg cost neurontin 2400 mg

  16. JosephWrela表示:

    prednisone 40 mg: prednisone 30 mg coupon – prednisone 20mg online

  17. Thanks for making me to get new suggestions about pc’s. I also possess the belief that one of the best ways to keep your laptop computer in prime condition is by using a hard plastic material case, or perhaps shell, that suits over the top of your computer. A majority of these protective gear tend to be model specific since they are made to fit perfectly in the natural housing. You can buy them directly from owner, or from third party sources if they are intended for your notebook, however not all laptop may have a covering on the market. All over again, thanks for your points.

  18. These player characters (PCs) can interact with one another and with characters that the pc controls — these are non-participant characters (NPCs).

  19. AlfredHag表示:

    purchase prednisone from india cost of prednisone 5mg tablets prednisone 10 mg price

  20. AlfredHag表示:

    where to get ventolin cheap Ventolin inhaler best price ventolin 500 mg

  21. More photos of our XC course might be seen right here.

  22. This way, the picture seems precisely as horns look in the actual world.

  23. In today’s episode of cool PFP concepts, we’ll tackle concepts for demon slayer followers.

  24. Billy calls out the name of a person who hasn’t yet acquired the ball (say, Sally), then he tosses the ball to Sally.

  25. JosephWrela表示:

    furosemide 40mg: furosemide online – lasix furosemide

  26. Excellent goods from you, man. I have understand your stuff previous to and you’re just too fantastic. I actually like what you’ve acquired here, certainly like what you are saying and the way in which you say it. You make it entertaining and you still care for to keep it smart. I cant wait to read far more from you. This is actually a terrific web site.

  27. ArnoldDRODA表示:

    neurontin 2018: how to get neurontin cheap – buy gabapentin

  28. Sergiohex表示:

    https://ventolininhaler.pro/# ventolin nebules

  29. zentai表示:

    I would also love to add if you do not currently have an insurance policy or you do not remain in any group insurance, you may well really benefit from seeking the aid of a health broker. Self-employed or people who have medical conditions typically seek the help of the health insurance specialist. Thanks for your writing.

發佈留言

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