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

14,727 Responses

  1. I believe that avoiding packaged foods may be the first step to be able to lose weight. They can taste beneficial, but prepared foods contain very little nutritional value, making you eat more to have enough vitality to get with the day. For anyone who is constantly taking in these foods, transitioning to cereals and other complex carbohydrates will aid you to have more energy while feeding on less. Great blog post.

  2. MauriceGueda表示:

    cheapest online pharmacy india: indian pharmacy paypal – buy prescription drugs from india

  3. RobertMef表示:

    aricept online pharmacy: cheapest pharmacy to get concerta – loratadine pharmacy choice

  4. Отличный сайт! Всем рекомендую!салон оптики

  5. RobertMef表示:

    viagra professional online pharmacy: Hyzaar – kroger pharmacy online

  6. You can certainly see your skills in the work you write. The world hopes for more passionate writers like you who aren’t afraid to say how they believe. Always follow your heart.

  7. I have read several good stuff here. Certainly worth bookmarking for revisiting. I surprise how much effort you put to create such a magnificent informative website.

  8. Pretty great post. I simply stumbled upon your blog and wished to say that I have truly enjoyed surfing around your weblog posts. In any case I?ll be subscribing to your rss feed and I am hoping you write once more very soon!

  9. RobertMef表示:

    mexican drugstore online: medicine in mexico pharmacies – buying from online mexican pharmacy

  10. Отличный сайт! Всем рекомендую!очки купить в Москве

  11. One important issue is that when you are searching for a education loan you may find that you will want a cosigner. There are many circumstances where this is correct because you might find that you do not have a past credit history so the loan company will require that you have someone cosign the loan for you. Interesting post.

  12. Nearly all of what you point out happens to be supprisingly legitimate and it makes me wonder the reason why I hadn’t looked at this in this light before. Your piece truly did turn the light on for me as far as this particular subject matter goes. However there is actually one factor I am not too comfortable with and whilst I try to reconcile that with the actual main theme of your position, let me observe just what all the rest of the readers have to point out.Very well done.

  13. Josephfub表示:

    pharmacies in mexico that ship to usa mexican border pharmacies shipping to usa mexican pharmaceuticals online

  14. Josephfub表示:

    mexico drug stores pharmacies purple pharmacy mexico price list mexican pharmaceuticals online

  15. Josephfub表示:

    best online pharmacies in mexico mexico pharmacies prescription drugs pharmacies in mexico that ship to usa

  16. ArthurKib表示:

    https://pharmbig24.online/# overseas pharmacy no prescription

  17. ArthurKib表示:

    http://pharmbig24.com/# inhouse pharmacy propecia

  18. What an insightful and thoroughly-researched article! The author’s thoroughness and ability to present complicated ideas in a comprehensible manner is truly commendable. I’m totally captivated by the depth of knowledge showcased in this piece. Thank you, author, for offering your wisdom with us. This article has been a real game-changer!

  19. Upmjzw表示:

    buy lioresal for sale – cheap feldene 20 mg buy feldene 20 mg

  20. RobertMef表示:

    top online pharmacy india: buy prescription drugs from india – indian pharmacies safe

  21. Hello! I’m at work browsing your blog from my new iphone 3gs! Just wanted to say I love reading through your blog and look forward to all your posts! Keep up the excellent work!

  22. I just added this weblog to my feed reader, excellent stuff. Cannot get enough!

  23. RobertMef表示:

    fluconazole tesco pharmacy: pharmacy prices – synthroid online pharmacy

  24. MauriceGueda表示:

    irmat pharmacy: best online pharmacy generic cialis – best online pharmacy no prescription cialis

  25. MauriceGueda表示:

    cialis daily: concerta pharmacy prices – viagra online pharmacy usa

  26. MauriceGueda表示:

    lipitor pharmacy card: skelaxin pharmacy – Singulair

  27. Another thing I have really noticed is that for many people, a bad credit score is the reaction of circumstances further than their control. For instance they may happen to be saddled with illness and because of this they have higher bills going to collections. Maybe it’s due to a work loss or perhaps the inability to go to work. Sometimes divorce can send the finances in a downward direction. Many thanks for sharing your ideas on this site.

發佈留言

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