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

  1. Bernardshoor表示:

    pharmacie en ligne livraison europe: Pharmacie sans ordonnance – Pharmacie en ligne livraison Europe pharmafst.com

  2. Bernardshoor表示:

    Tadalafil 20 mg prix sans ordonnance: Cialis sans ordonnance 24h – Cialis sans ordonnance 24h tadalmed.shop

  3. Bernardshoor表示:

    Tadalafil 20 mg prix en pharmacie: Tadalafil 20 mg prix sans ordonnance – Cialis generique prix tadalmed.shop

  4. Robertfap表示:

    http://kamagraprix.com/# kamagra pas cher

  5. I do agree with all the ideas you have presented in your post. They’re very convincing and will definitely work. Still, the posts are too short for novices. Could you please extend them a little from next time? Thanks for the post.

  6. Thank you for some other excellent article. The place else may anybody get that type of info in such an ideal approach of writing? I have a presentation subsequent week, and I am on the search for such info.

  7. Robertfap表示:

    https://kamagraprix.com/# kamagra 100mg prix

  8. Thanks for your article. I would like to say that your health insurance agent also works best for the benefit of the coordinators of any group insurance cover. The health insurance professional is given a long list of benefits desired by a person or a group coordinator. What any broker does is try to find individuals or perhaps coordinators which will best match those desires. Then he gifts his ideas and if both sides agree, the broker formulates a binding agreement between the 2 parties.

  9. game slot表示:

    It’s great that you are getting ideas from this paragraph as well asfrom our discussion made here.

  10. One thing I would like to comment on is that fat reduction plan fast can be carried out by the right diet and exercise. A person’s size not merely affects the look, but also the overall quality of life. Self-esteem, major depression, health risks, along with physical capabilities are affected in excess weight. It is possible to make everything right and at the same time having a gain. In such a circumstance, a problem may be the perpetrator. While an excessive amount of food instead of enough exercising are usually at fault, common medical ailments and trusted prescriptions can certainly greatly amplify size. Thanks alot : ) for your post in this article.

  11. Robertfap表示:

    https://tadalmed.com/# Acheter Cialis

  12. I’ve really noticed that credit restoration activity really needs to be conducted with tactics. If not, you are going to find yourself endangering your rank. In order to succeed in fixing your credit ranking you have to verify that from this instant you pay all your monthly expenses promptly prior to their timetabled date. It really is significant for the reason that by not necessarily accomplishing that, all other methods that you will decide to try to improve your credit positioning will not be powerful. Thanks for revealing your tips.

  13. Bernardshoor表示:

    acheter mГ©dicament en ligne sans ordonnance: Livraison rapide – pharmacie en ligne sans ordonnance pharmafst.com

  14. I liked as much as you’ll obtain performed right here. The cartoon is attractive, your authored material stylish. however, you command get bought an nervousness over that you would like be delivering the following. sick undoubtedly come more in the past again since precisely the same just about very continuously inside of case you shield this hike.

  15. Bernardshoor表示:

    cialis sans ordonnance: Tadalafil sans ordonnance en ligne – Cialis sans ordonnance 24h tadalmed.shop

  16. Bernardshoor表示:

    Cialis generique prix: Acheter Viagra Cialis sans ordonnance – Cialis sans ordonnance 24h tadalmed.shop

  17. услуги по продаже аккаунтов профиль с подписчиками

  18. BillieLet表示:

    kamagra 100mg prix: kamagra gel – acheter kamagra site fiable

  19. I have recently started a website, the info you offer on this site has helped me tremendously. Thank you for all of your time & work.

  20. Thanks for the suggestions you reveal through this website. In addition, a lot of young women exactly who become pregnant will not even try to get medical health insurance because they dread they won’t qualify. Although a few states at this moment require that insurers produce coverage in spite of the pre-existing conditions. Charges on all these guaranteed plans are usually greater, but when thinking about the high cost of health care it may be your safer route to take to protect a person’s financial future.

  21. I have been browsing online more than 3 hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. Personally, if all website owners and bloggers made good content as you did, the internet will be much more useful than ever before.

  22. Robertfap表示:

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

  23. маркетплейс аккаунтов соцсетей профиль с подписчиками

  24. BillieLet表示:

    Cialis en ligne: cialis generique – Cialis generique prix tadalmed.shop

  25. Peterclada表示:

    Pharmacie en ligne livraison Europe pharmacie en ligne pas cher trouver un mГ©dicament en pharmacie pharmafst.shop

  26. CharlieMougs表示:

    kraken вход – кракен войти, кракен клир

  27. Bernardshoor表示:

    pharmacie en ligne france livraison belgique: Medicaments en ligne livres en 24h – pharmacie en ligne sans ordonnance pharmafst.com

  28. Электропривод для горизонтальных жалюзи доставка по всей стране
    электропривод для горизонтальных жалюзи электропривод для горизонтальных жалюзи .

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

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