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

16,003 Responses

  1. HaroldBig表示:

    Ozempic without insurance: Ozempic without insurance – ozempic cost

  2. I believe this is one of the so much significant information for me. And i’m happy reading your article. However want to observation on few basic things, The website style is great, the articles is in point of fact excellent : D. Just right task, cheers

  3. Профессиональный сервисный центр по ремонту объективов в Москве.
    Мы предлагаем: ремонт объективов в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  4. Jeremypag表示:

    rybelsus coupon rybelsus coupon semaglutide tablets

  5. Frankevild表示:

    https://ozempic.art/# ozempic cost

  6. BarryDof表示:

    http://ozempic.art/# ozempic coupon

  7. I was very pleased to find this internet-site.I wished to thanks on your time for this glorious learn!! I positively enjoying each little little bit of it and I’ve you bookmarked to check out new stuff you blog post.

  8. Hello There. I found your blog using msn. This is an extremely well written article. I will be sure to bookmark it and return to read more of your useful info. Thanks for the post. I will certainly comeback.

  9. HaroldBig表示:

    semaglutide online: semaglutide tablets – semaglutide online

  10. lesbian porn表示:

    Very nice post. I just stumbled upon your weblog and wanted to say that I’ve truly loved surfing around your weblog posts. After all I?ll be subscribing on your rss feed and I’m hoping you write once more soon!

  11. gay porn表示:

    Usually I do not read post on blogs, but I wish to say that this write-up very forced me to check out and do so! Your writing style has been surprised me. Thanks, quite nice post.

  12. I think that a foreclosed can have a important effect on the client’s life. House foreclosures can have a 8 to few years negative relation to a client’s credit report. A new borrower who may have applied for home financing or any kind of loans for example, knows that a worse credit rating is actually, the more complicated it is to acquire a decent financial loan. In addition, it could affect a borrower’s capacity to find a reasonable place to let or hire, if that results in being the alternative property solution. Good blog post.

  13. Профессиональный сервисный центр по ремонту сигвеев в Москве.
    Мы предлагаем: segway ремонт
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  14. Профессиональный сервисный центр по ремонту сетевых хранилищ в Москве.
    Мы предлагаем: надежный сервис ремонта сетевых хранилищ
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  15. RamonRek表示:

    buy semaglutide pills: rybelsus coupon – semaglutide online

  16. Porn video表示:

    I’m really enjoying the design and layout of your website. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a developer to create your theme? Excellent work!

  17. Jeremypag表示:

    buy semaglutide online semaglutide online rybelsus coupon

  18. BarryDof表示:

    http://ozempic.art/# Ozempic without insurance

  19. HaroldBig表示:

    rybelsus cost: buy rybelsus online – rybelsus price

  20. Thanks for the recommendations you have shared here. Something else I would like to mention is that personal computer memory demands generally rise along with other advances in the technological know-how. For instance, if new generations of processor chips are made in the market, there is certainly usually a related increase in the size preferences of both laptop or computer memory along with hard drive room. This is because the software operated by these processors will inevitably boost in power to leverage the new technologies.

  21. There are some attention-grabbing time limits in this article but I don?t know if I see all of them heart to heart. There’s some validity however I will take hold opinion until I look into it further. Good article , thanks and we wish extra! Added to FeedBurner as properly

  22. Frankevild表示:

    https://ozempic.art/# ozempic

  23. From my examination, shopping for electronic devices online can for sure be expensive, nevertheless there are some principles that you can use to acquire the best offers. There are usually ways to uncover discount deals that could help to make one to possess the best consumer electronics products at the smallest prices. Good blog post.

  24. Hey There. I found your blog using msn. This is a really well written article. I?ll be sure to bookmark it and return to read more of your useful information. Thanks for the post. I?ll certainly return.

  25. Hey very cool web site!! Man .. Beautiful .. Amazing .. I will bookmark your site and take the feeds also?I am happy to find numerous useful information here in the post, we need develop more strategies in this regard, thanks for sharing. . . . . .

  26. pravo751obliz表示:

    Заказать грамотное юридическое сопровождение можно на нашем сайте.

  27. Heya i?m for the first time here. I came across this board and I find It truly useful & it helped me out much. I hope to give something back and help others like you aided me.

  28. Just wish to say your article is as amazing. The clearness in your post is just excellent and i can assume you are an expert on this subject. Well with your permission let me to grab your feed to keep up to date with forthcoming post. Thanks a million and please keep up the rewarding work.

  29. Сервисный центр предлагает срочный ремонт стиральных машин lg качественый ремонт стиральных машин lg

發佈留言

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