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

35,321 Responses

  1. Along with every thing that seems to be developing inside this specific subject material, a significant percentage of viewpoints happen to be rather refreshing. Nonetheless, I beg your pardon, because I can not give credence to your entire theory, all be it radical none the less. It seems to me that your commentary are generally not completely rationalized and in fact you are your self not even totally confident of the point. In any event I did appreciate looking at it.

  2. We stumbled over here different website and thought I may as well check things out. I like what I see so now i am following you. Look forward to going over your web page for a second time.

  3. Michaelscoob表示:

    Lisin Express: Lisin Express – lisinopril india price

  4. Danieldrymn表示:

    lisinopril 102: Lisin Express – Lisin Express

  5. Danieldrymn表示:

    can we buy amoxcillin 500mg on ebay without prescription: AmOnlinePharm – AmOnlinePharm

  6. Mia Jones表示:

    If you’re a property owner looking to get a loan, a secured loan could be a sensible option. Access better rates by using your home as collateral.

  7. Thanks for the concepts you talk about through this web site. In addition, a lot of young women who become pregnant will not even attempt to get medical health insurance because they worry they might not qualify. Although many states at this point require that insurers give coverage in spite of the pre-existing conditions. Rates on these kinds of guaranteed programs are usually larger, but when with the high cost of health care it may be a safer approach to take to protect the financial future.

  8. qq88表示:

    I adore your wordpress web template, wherever do you download it through?

  9. LanceFen表示:

    Lisin Express: buy cheap lisinopril – lisinopril 3.5 mg

  10. Hi, I think your website might be having browser compatibility issues. When I look at your website in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, wonderful blog!

  11. Michaelscoob表示:

    ZithPharmOnline: ZithPharmOnline – zithromax buy online

  12. Richardaudit表示:

    https://lisinexpress.com/# buy lisinopril 20 mg

  13. Not sure if a secured loan is right for you? Understand the benefits, such as lower interest rates and larger borrowing amounts.

  14. My brother recommended I might like this web site. He was totally right. This post truly made my day. You can not imagine just how much time I had spent for this info! Thanks!

  15. bet88dog表示:

    It?s really a nice and useful piece of information. I am happy that you just shared this useful info with us. Please keep us informed like this. Thank you for sharing.

  16. alarme Ajax表示:

    I’ve been absent for some time, but now I remember why I used to love this blog. Thanks , I will try and check back more frequently. How frequently you update your web site?

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

  18. Danieldrymn表示:

    AmOnlinePharm: AmOnlinePharm – amoxicillin 500mg pill

  19. Michaelscoob表示:

    ZithPharmOnline: ZithPharmOnline – ZithPharmOnline

  20. qq88表示:

    I?ve read a few excellent stuff here. Definitely price bookmarking for revisiting. I wonder how so much attempt you set to make this type of wonderful informative website.

  21. ai notes pdf表示:

    Wow, great blog.Really thank you!

  22. mostbet_ecer表示:

    мостбет казино мостбет казино .

  23. qq88表示:

    Thank you for another informative site. Where else could I get that kind of information written in such an ideal way? I’ve a project that I am just now working on, and I’ve been on the look out for such information.

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

  25. Richardaudit表示:

    https://lisinexpress.shop/# Lisin Express

  26. My brother suggested I may like this web site. He used to be totally right. This publish truly made my day. You cann’t believe just how so much time I had spent for this info! Thank you!

  27. Michaelscoob表示:

    prinzide zestoretic: Lisin Express – Lisin Express

  28. qq88表示:

    Thanks for any other informative website. Where else may I am getting that type of info written in such an ideal method? I have a project that I’m simply now running on, and I have been at the glance out for such information.

  29. BrianTom表示:

    Pred Pharm Net Pred Pharm Net prednisone for dogs

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

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