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

39,133 Responses

  1. Thanks for some other excellent post. The place else may just anybody get that type of info in such a perfect manner of writing? I have a presentation next week, and I am at the search for such information.

  2. This is the kind of writing I look for.

  3. hi!,I like your writing so much! share we communicate more about your article on AOL? I need a specialist on this area to solve my problem. May be that’s you! Looking forward to see you.

  4. Mark Jones表示:

    I absolutely admired the way this was explained.

  5. hello!,I like your writing so much! share we communicate more about your article on AOL? I require a specialist on this area to solve my problem. May be that’s you! Looking forward to see you.

  6. ScottTrefs表示:

    cialis pill: Tadal Access – e-cialis hellocig e-liquid

  7. LorenOmigo表示:

    cialis commercial bathtub: cialis canadian purchase – cialis walgreens

  8. Great write-up, I?m normal visitor of one?s blog, maintain up the nice operate, and It is going to be a regular visitor for a long time.

  9. LorenOmigo表示:

    buy cialis canada: TadalAccess – cialis online pharmacy australia

  10. Профессиональный сервисный центр по ремонту техники в Екатеринбурге.
    Мы предлагаем: Сколько стоит отремонтировать телевизор Hisense
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  11. Paul Lewis表示:

    The depth in this write-up is remarkable.

  12. LorenOmigo表示:

    cialis using paypal in australia: TadalAccess – cialis generic cvs

  13. I have realized that car insurance providers know the motors which are vulnerable to accidents along with risks. In addition, they know what sort of cars are given to higher risk as well as the higher risk they’ve already the higher your premium price. Understanding the very simple basics associated with car insurance just might help you choose the right types of insurance policy which will take care of your needs in case you become involved in any accident. Many thanks sharing a ideas on the blog.

  14. I can’t express how much I admire the effort the author has put into producing this outstanding piece of content. The clarity of the writing, the depth of analysis, and the wealth of information presented are simply impressive. His passion for the subject is apparent, and it has definitely made an impact with me. Thank you, author, for offering your wisdom and enhancing our lives with this extraordinary article!

  15. Peter White表示:

    This article is top-notch.

  16. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт холодильников gorenje, можете посмотреть на сайте: ремонт холодильников gorenje в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  17. I have learned some new things from the blog post. One other thing to I have seen is that usually, FSBO sellers may reject people. Remember, they’d prefer to not ever use your products and services. But if you actually maintain a gentle, professional partnership, offering assistance and being in contact for about four to five weeks, you will usually be capable of win a meeting. From there, a house listing follows. Thank you

  18. Josephmew表示:

    where to get the best price on cialis TadalAccess cialis from mexico

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

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