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

22,860 Responses

  1. Hello my friend! I want to say that this post is awesome, great written and include almost all significant infos. I would like to look extra posts like this .

  2. DanielAbice表示:

    http://prednibest.com/# 5 prednisone in mexico

  3. Interesting article. It is rather unfortunate that over the last ten years, the travel industry has already been able to to handle terrorism, SARS, tsunamis, bird flu, swine flu, as well as the first ever real global economic downturn. Through everthing the industry has really proven to be strong, resilient as well as dynamic, finding new solutions to deal with hardship. There are often fresh challenges and possibilities to which the industry must once more adapt and reply.

  4. KennethPah表示:

    cost of generic clomid pills clomid on pharm can i get generic clomid pills

  5. конвертер юань в тенге калькулятор .

    Онлайн-сервис с мгновенной конвертацией валют: переведите тенге в рубли, доллары США или юани за считаные секунды. Точные курсы валют обновляются в режиме реального времени.

  6. Thanks for your exciting article. Other thing is that mesothelioma is generally caused by the inhalation of material from asbestos, which is a extremely dangerous material. It can be commonly noticed among staff in the structure industry who may have long contact with asbestos. It is also caused by living in asbestos insulated buildings for a long period of time, Genetic makeup plays an important role, and some people are more vulnerable towards the risk as compared to others.

  7. вывод из запоя спб цены [url=https://www.taksafonchik.borda.ru/?1-2-0-00001309-000-0-0-1730826374]вывод из запоя спб цены[/url] .

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

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

  10. I’ve been surfing online more than three hours today, yet I never found any interesting article like yours. It?s pretty worth enough for me. Personally, if all site owners and bloggers made good content as you did, the net will be much more useful than ever before.

  11. I’m not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come back down the road. All the best

  12. DanielAbice表示:

    https://clomidonpharm.com/# can i get clomid no prescription

  13. SamuelBix表示:

    prednisone 40 mg: PredniBest – prednisone online for sale

  14. Mostbet PL表示:

    Hey just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Internet explorer. I’m not sure if this is a formatting issue or something to do with internet browser compatibility but I figured I’d post to let you know. The style and design look great though! Hope you get the problem fixed soon. Cheers

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

  16. I haven?t checked in here for a while because I thought it was getting boring, but the last few posts are good quality so I guess I will add you back to my everyday bloglist. You deserve it my friend 🙂

  17. One thing I’ve noticed is that often there are plenty of common myths regarding the financial institutions intentions when talking about foreclosures. One fantasy in particular is always that the bank prefers to have your house. The lender wants your dollars, not the home. They want the amount of money they gave you together with interest. Staying away from the bank will still only draw a new foreclosed conclusion. Thanks for your article.

  18. Thank you for another informative website. The place else may just I am getting that kind of information written in such a perfect approach? I’ve a mission that I am just now working on, and I’ve been on the look out for such info.

  19. Thank you for another wonderful article. Where else could anyone get that kind of info in such an ideal way of writing? I have a presentation next week, and I am on the look for such info.

  20. DanielAbice表示:

    https://cipharmdelivery.com/# where can i buy cipro online

  21. KennethPah表示:

    buy cipro without rx buy cipro online without prescription buy cipro online canada

  22. Mostbet PL表示:

    I appreciate, cause I found exactly what I was looking for. You have ended my 4 day long hunt! God Bless you man. Have a nice day. Bye

  23. Hello, i think that i saw you visited my web site so i came to ?return the favor?.I’m attempting to find things to improve my web site!I suppose its ok to use some of your ideas!!

  24. Mostbet PL表示:

    Thanks for your marvelous posting! I definitely enjoyed reading it, you can be a great author.I will make sure to bookmark your blog and definitely will come back at some point. I want to encourage continue your great writing, have a nice weekend!

發佈留言

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