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

  1. KennethPah表示:

    buying generic clomid no prescription can you buy clomid without dr prescription where can i get clomid tablets

  2. Hi there, just became alert to your blog through Google, and found that it’s really informative. I?m gonna watch out for brussels. I?ll appreciate if you continue this in future. Numerous people will be benefited from your writing. Cheers!

  3. Hi there, You’ve done an incredible job. I will definitely digg it and personally recommend to my friends. I’m confident they’ll be benefited from this website.

  4. Joe Martin (February 9, 2012).

  5. They made their dwelling near Jay, Okay.

  6. UK – Studiomaster, the UK headquartered MI and pro audio model, has signed a serious MI and professional audio retail distribution agreement with EMD Music, for Austria, Belgium, France, Germany, Luxembourg, Netherlands and Switzerland.

  7. KennethPah表示:

    how to get clomid without a prescription clomidonpharm where can i get clomid without prescription

  8. анонимный чат поговори со мной анонимный чат поговори со мной .

  9. great issues altogether, you simply won a emblem new reader. What might you suggest in regards to your put up that you simply made a few days in the past? Any positive?

  10. My spouse and I stumbled over here by a different web page and thought I should check things out. I like what I see so i am just following you. Look forward to checking out your web page again.

  11. onexbet_euot表示:

    Самый популярный букмекер onexbet, присоединяйтесь и выигрывайте|Успешные ставки на спорт с onexbet, ставьте деньги и получайте прибыль|Надежный букмекер onexbet, зарабатывайте без стресса|Больше шансов на успех с onexbet, участвуйте в акциях и выигрывайте|Большой выбор азартных игр на onexbet, не упустите шанс стать миллионером|Быстрые выплаты на onexbet, важны ваш комфорт и удобство|Законные ставки на onexbet, играйте честно и законно|Онлайн трансляции спортивных событий на onexbet, выигрывайте, не выходя из дома|Получайте эксклюзивные предложения от onexbet, не упустите шанс стать богаче|Азартные игры с живыми дилерами на onexbet, получайте эмоции и азарт вместе с onexbet|Большой выбор спортивных событий на onexbet, онлайн ставки на спорт с onexbet – ваш успех|Делайте выгодные прогнозы и зарабатывайте, ставьте на успешных букмекеров|Лучшие коэффициенты и выигрыши на onexbet, выигрывайте больше, чем раньше|Ваш комфорт – наш приоритет, наши специалисты помогут вам 24/7|Легкость использования и простота на onexbet, играйте без стресса и неудобств|Большие джекпоты на onexbet, ставьте и получайте крупные выигрыши|Зарабатывайте на ставках с onexbet, не упустите шанс улучшить свою финансовую ситуацию|Играйте и зарабатывайте больше, получайте индивидуальные предложения и бонусы|Получайте прибыль от онлайн ставок на onexbet, делайте прогнозы и получайте прибыль|Профессиональная букмекерская контора onex
    1 one x bet 1 one x bet .

  12. SamuelBix表示:

    amoxicillin 500 mg cost: Amox Star – price of amoxicillin without insurance

  13. DanielAbice表示:

    http://prednibest.com/# how much is prednisone 10mg

  14. Louisiana presents schooling assistance to surviving spouses of deceased veterans in addition to youngsters of 90 or higher disabled veterans and children of 100 disabled and unemployable veterans.

  15. SamuelBix表示:

    can you purchase amoxicillin online: amoxicillin azithromycin – buying amoxicillin online

  16. I have noticed that in video cameras, specialized receptors help to {focus|concentrate|maintain focus|target|a**** automatically. The sensors connected with some video cameras change in in the area of contrast, while others use a beam of infra-red (IR) light, specially in low lumination. Higher standards cameras from time to time use a mix of both techniques and will often have Face Priority AF where the photographic camera can ‘See’ a face and concentrate only upon that. Thanks for sharing your notions on this web site.

  17. I think this is among the such a lot significant information for me. And i am satisfied reading your article. However want to remark on few common things, The website style is ideal, the articles is in point of fact excellent : D. Just right activity, cheers

  18. Mrs. Birch died this morning at Houston County Nursing Home in Crockett.

  19. whoah this weblog is great i like reading your posts. Stay up the great work! You know, many people are looking around for this info, you can aid them greatly.

  20. Avoid touching produce and other objects.

  21. My brother suggested I might like this website. He was entirely right. This post actually made my day. You can not imagine just how much time I had spent for this info! Thanks!

  22. Hello! Someone in my Facebook group shared this site with us so I came to look it over. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Wonderful blog and amazing style and design.

  23. DanielAbice表示:

    https://cipharmdelivery.com/# ciprofloxacin generic

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

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

  26. In previous world championships, the gamers adopted a easy two days on, one time without work schedule.

  27. on the grill表示:

    My brother suggested I might like this blog. He was entirely right. This post truly made my day. You cann’t imagine just how much time I had spent for this info! Thanks!

  28. 突 とは表示:

    For folks with these issues, Threads federation is a reasonably large step toward being ready to maintain an account on Mastodon (or one other fediverse service) and still discover the folks they need to interact with-assuming a few of these persons are on Threads and never only on Bluesky, Twitter/X, Instagram, and all the other non-ActivityPub-powered techniques.

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

  30. SamuelBix表示:

    buy amoxil: amoxicillin tablet 500mg – buy amoxicillin 500mg canada

發佈留言

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