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

37,508 Responses

  1. Bernardshoor表示:

    Cialis sans ordonnance 24h: Acheter Cialis – Achat Cialis en ligne fiable tadalmed.shop

  2. 牛樟芝液表示:

    Hi there just wanted to give you a brief heads up and let you know a few of the images aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same results.

  3. Bernardshoor表示:

    pharmacie en ligne france pas cher: Livraison rapide – pharmacie en ligne france fiable pharmafst.com

  4. Peterclada表示:

    Cialis generique prix Acheter Cialis Tadalafil sans ordonnance en ligne tadalmed.com

  5. Superb post but I was wondering if you could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit more. Kudos!

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

  7. Robertfap表示:

    http://tadalmed.com/# Tadalafil sans ordonnance en ligne

  8. I’m in awe of the author’s capability to make complicated concepts approachable to readers of all backgrounds. This article is a testament to her expertise and passion to providing helpful insights. Thank you, author, for creating such an compelling and enlightening piece. It has been an absolute pleasure to read!

  9. Peterclada表示:

    pharmacie en ligne livraison europe pharmacie en ligne pas cher pharmacie en ligne france livraison internationale pharmafst.shop

  10. Hey! I just want to give a huge thumbs up for the nice data you have got here on this post. I will probably be coming again to your blog for extra soon.

  11. Hey! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

  12. BillieLet表示:

    trouver un mГ©dicament en pharmacie: pharmacie en ligne – Achat mГ©dicament en ligne fiable pharmafst.com

  13. Robertfap表示:

    https://tadalmed.shop/# Cialis generique prix

  14. BradleyJaire表示:

    pharmacie en ligne france fiable: pharmacie en ligne sans ordonnance – pharmacie en ligne pas cher pharmafst.com

  15. you’re really a good webmaster. The site loading speed is amazing. It seems that you’re doing any unique trick. Moreover, The contents are masterwork. you have done a wonderful job on this topic!

  16. BillieLet表示:

    Achetez vos kamagra medicaments: Kamagra Oral Jelly pas cher – kamagra livraison 24h

  17. I am really loving the theme/design of your website. Do you ever run into any browser compatibility problems? A couple of my blog visitors have complained about my blog not operating correctly in Explorer but looks great in Firefox. Do you have any tips to help fix this issue?

  18. hello there and thanks in your info ? I?ve certainly picked up anything new from proper here. I did however expertise several technical issues the usage of this website, since I experienced to reload the site many instances previous to I may just get it to load correctly. I had been brooding about if your web hosting is OK? No longer that I’m complaining, however sluggish loading circumstances times will very frequently have an effect on your placement in google and could injury your high quality ranking if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Anyway I am including this RSS to my e-mail and can look out for a lot extra of your respective exciting content. Ensure that you replace this again very soon..

  19. 白牛樟芝表示:

    Thanks for the ideas shared on the blog. Yet another thing I would like to convey is that losing weight is not all about going on a dietary fad and trying to get rid of as much weight as you can in a few months. The most effective way in losing weight is by consuming it bit by bit and using some basic guidelines which can assist you to make the most from a attempt to shed weight. You may realize and already be following many of these tips, yet reinforcing expertise never does any damage.

  20. Hey there! I’m at work surfing around your blog from my new iphone 4! Just wanted to say I love reading your blog and look forward to all your posts! Carry on the excellent work!

  21. Robertfap表示:

    http://kamagraprix.com/# kamagra livraison 24h

  22. Peterclada表示:

    Acheter Kamagra site fiable Kamagra pharmacie en ligne Kamagra pharmacie en ligne

  23. Bernardshoor表示:

    kamagra en ligne: kamagra gel – achat kamagra

  24. Wow, incredible blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is fantastic, as well as the content!

發佈回覆給「BobbyAroma」的留言 取消回覆

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