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

11,329 Responses

  1. What i do not understood is actually how you’re not actually much more well-liked than you may be right now. You are so intelligent. You realize therefore considerably relating to this subject, made me personally consider it from a lot of varied angles. Its like men and women aren’t fascinated unless it?s one thing to accomplish with Lady gaga! Your own stuffs excellent. Always maintain it up!

  2. There are some fascinating deadlines in this article however I don?t know if I see all of them middle to heart. There may be some validity but I will take maintain opinion until I look into it further. Good article , thanks and we want extra! Added to FeedBurner as effectively

  3. vk chamoflove表示:

    Oh my goodness! an incredible article dude. Thank you However I’m experiencing difficulty with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting similar rss problem? Anybody who knows kindly respond. Thnkx

  4. Leonardpar表示:

    http://mexicopharmacy.win/# mexican rx online

  5. DouglasGed表示:

    reputable mexican pharmacies online: Purple pharmacy online ordering – reputable mexican pharmacies online

  6. DouglasGed表示:

    cheap erectile dysfunction pills: buy ed medication – boner pills online

  7. Good day! I know this is kind of off topic but I was wondering which blog platform are you using for this site? I’m getting fed up of WordPress because I’ve had issues with hackers and I’m looking at options for another platform. I would be fantastic if you could point me in the direction of a good platform.

  8. Charleshon表示:

    https://indiapharmacy.shop/# Online medicine home delivery
    ed medicines

  9. DouglasGed表示:

    mexican pharmaceuticals online: Best online Mexican pharmacy – pharmacies in mexico that ship to usa

  10. This actually answered my problem, thank you!

  11. One other issue is when you are in a situation where you would not have a cosigner then you may really want to try to wear out all of your school funding options. You will find many awards and other grants that will offer you funding to aid with school expenses. Thank you for the post.

  12. Charleshon表示:

    https://mexicopharmacy.win/# buying from online mexican pharmacy
    online ed drugs

  13. Interesting blog post. The things i would like to contribute is that personal computer memory must be purchased if your computer cannot cope with anything you do with it. One can deploy two RAM boards with 1GB each, as an illustration, but not certainly one of 1GB and one of 2GB. One should make sure the maker’s documentation for one’s PC to be sure what type of ram is needed.

  14. I?m impressed, I need to say. Actually hardly ever do I encounter a weblog that?s both educative and entertaining, and let me let you know, you have got hit the nail on the head. Your concept is outstanding; the issue is something that not enough individuals are speaking intelligently about. I am very pleased that I stumbled across this in my search for something regarding this.

  15. The following time I learn a blog, I hope that it doesnt disappoint me as much as this one. I mean, I do know it was my choice to read, but I truly thought youd have something interesting to say. All I hear is a bunch of whining about something that you could possibly fix when you werent too busy on the lookout for attention.

  16. I think other site proprietors should take this site as an model, very clean and wonderful user genial style and design, let alone the content. You are an expert in this topic!

  17. Eievle表示:

    duphalac canada – buy betahistine 16mg without prescription order betahistine 16mg without prescription

  18. Great blog you have here but I was wanting to know if you knew of any message boards that cover the same topics talked about in this article? I’d really like to be a part of community where I can get feedback from other experienced individuals that share the same interest. If you have any suggestions, please let me know. Appreciate it!

  19. I have been surfing online greater than 3 hours today, but I by no means found any interesting article like yours. It?s lovely price sufficient for me. Personally, if all website owners and bloggers made good content as you did, the internet will probably be a lot more helpful than ever before.

  20. I think other site proprietors should take this website as an model, very clean and excellent user genial style and design, let alone the content. You’re an expert in this topic!

  21. Charleshon表示:

    https://edpillpharmacy.store/# online ed prescription
    cheapest ed online

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

  23. you’ve gotten an ideal weblog right here! would you prefer to make some invite posts on my weblog?

  24. Samueldub表示:

    http://tadalafil.auction/# cialis canada generic

  25. Pretty element of content. I just stumbled upon your site and in accession capital to assert that I acquire in fact loved account your blog posts. Anyway I?ll be subscribing on your augment and even I fulfillment you get entry to constantly rapidly.

  26. Thanks for the different tips contributed on this web site. I have observed that many insurers offer customers generous special discounts if they choose to insure a couple of cars together. A significant volume of households have several cars or trucks these days, particularly those with older teenage youngsters still dwelling at home, plus the savings in policies might soon begin. So it pays to look for a good deal.

  27. yuumeilyn表示:

    Many thanks for this article. I’d also like to state that it can become hard if you find yourself in school and starting out to initiate a long credit standing. There are many learners who are just trying to pull through and have an extended or good credit history can sometimes be a difficult element to have.

  28. An attention-grabbing dialogue is worth comment. I feel that you should write more on this matter, it may not be a taboo subject but generally persons are not sufficient to talk on such topics. To the next. Cheers

  29. Mazrlsf表示:

    Добрый день!
    Как быстро и легально купить аттестат 11 класса в Москве
    diplomrushkan.ru

發佈留言

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