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

  1. Dino Game 126表示:

    Thanks for the diverse tips shared on this blog site. I have seen that many insurers offer shoppers generous special discounts if they decide to insure several cars with them. A significant number of households have several vehicles these days, specifically those with more aged teenage kids still residing at home, as well as savings for policies can soon mount up. So it is a good idea to look for a bargain.

  2. Dino Game 121表示:

    Wonderful blog! I found it while surfing around on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Thank you

  3. I’m truly enjoying the design and layout of your website. 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!

  4. Sazrubw表示:

    Добрый день!
    Мы готовы предложить дипломы любой профессии.
    Покупка диплома, который подтверждает окончание института, – это выгодное решение.
    lolipopnews.ru/page/4
    Окажем помощь!.

  5. I?m impressed, I must say. Really rarely do I encounter a blog that?s both educative and entertaining, and let me tell you, you have hit the nail on the head. Your idea is excellent; the issue is one thing that not sufficient people are speaking intelligently about. I’m very comfortable that I stumbled across this in my seek for something relating to this.

  6. Dino Game 122表示:

    magnificent post, very informative. I wonder why the other specialists of this sector do not notice this. You must continue your writing. I’m confident, you have a huge readers’ base already!

  7. DanielTet表示:

    Cytotec 200mcg price https://furosemide.win/# lasix 100mg
    lasix 40 mg

  8. Dino Game 126表示:

    One important thing is that if you are searching for a education loan you may find that you will need a cosigner. There are many circumstances where this is correct because you will find that you do not employ a past credit history so the loan company will require that you’ve someone cosign the loan for you. Great post.

  9. DanielTet表示:

    cytotec abortion pill https://lipitor.guru/# buy lipitor from india
    furosemide 100mg

  10. One thing I would really like to say is the fact that before purchasing more personal computer memory, take a look at the machine within which it could be installed. When the machine is usually running Windows XP, for instance, a memory threshold is 3.25GB. The installation of over this would basically constitute just a waste. Be sure that one’s motherboard can handle an upgrade volume, as well. Great blog post.

  11. Would you be desirous about exchanging hyperlinks?

  12. I?ll immediately grab your rss feed as I can’t find your e-mail subscription link or newsletter service. Do you have any? Please let me know in order that I could subscribe. Thanks.

  13. Mazrfgo表示:

    Привет, друзья!
    Удивительно, но купить диплом кандидата наук оказалось не так сложно
    maps.google.is/url?q=aurus-diploms.com

  14. Dino Game 120表示:

    Music began playing anytime I opened this web site, so annoying!

  15. Dino Game 118表示:

    Thanks for the tips you discuss through this web site. In addition, a lot of young women that become pregnant will not even attempt to get medical care insurance because they dread they might not qualify. Although a few states today require that insurers offer coverage irrespective of the pre-existing conditions. Rates on these kind of guaranteed plans are usually greater, but when with the high cost of health care bills it may be some sort of a safer route to take to protect your own financial future.

  16. This website online is really a stroll-through for all of the data you wanted about this and didn?t know who to ask. Glimpse right here, and also you?ll undoubtedly discover it.

  17. I’m not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back later. Many thanks

  18. Thanks for giving your ideas. Something is that students have an alternative between national student loan along with a private education loan where it is easier to decide on student loan online debt consolidation than in the federal education loan.

  19. Jamesric表示:

    generic lipitor cost: buy lipitor 20mg – lipitor price in india

  20. Jamesric表示:

    lasix online: furosemide online – furosemide 40mg

  21. Dino Game 126表示:

    This is the suitable weblog for anybody who wants to find out about this topic. You realize a lot its virtually exhausting to argue with you (not that I truly would want?HaHa). You positively put a new spin on a subject thats been written about for years. Great stuff, just great!

  22. I have read several just right stuff here. Certainly price bookmarking for revisiting. I surprise how much attempt you set to make any such fantastic informative site.

  23. Jamesric表示:

    tamoxifen alternatives premenopausal: buy tamoxifen online – alternative to tamoxifen

  24. Dino Game 129表示:

    Useful info. Fortunate me I discovered your website unintentionally, and I’m surprised why this coincidence did not came about earlier! I bookmarked it.

  25. Hello there! This is my first comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading your articles. Can you suggest any other blogs/websites/forums that go over the same subjects? Thanks a ton!

  26. Just want to say your article is as astounding. The clearness to your submit is just excellent and that i could suppose you are a professional in this subject. Fine along with your permission allow me to clutch your RSS feed to keep up to date with coming near near post. Thanks one million and please carry on the enjoyable work.

  27. DanielTet表示:

    п»їcytotec pills online https://lipitor.guru/# lipitor 5 mg tablet
    lasix side effects

發佈留言

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