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

10,420 Responses

  1. Caliburn表示:

    Thanks for these guidelines. One thing I additionally believe is the fact credit cards offering a 0 interest rate often appeal to consumers together with zero interest rate, instant authorization and easy on the web balance transfers, however beware of the main factor that will certainly void your current 0 easy road annual percentage rate and throw you out into the terrible house quickly.

  2. Caliburn表示:

    Thanks for sharing excellent informations. Your website is very cool. I am impressed by the details that you?ve on this site. It reveals how nicely you perceive this subject. Bookmarked this website page, will come back for extra articles. You, my pal, ROCK! I found just the information I already searched all over the place and just could not come across. What a great web site.

  3. Flum flavors表示:

    There are certainly numerous particulars like that to take into consideration. That may be a great level to convey up. I supply the thoughts above as common inspiration but clearly there are questions just like the one you bring up the place an important thing will likely be working in sincere good faith. I don?t know if finest practices have emerged around things like that, but I am sure that your job is clearly identified as a good game. Each girls and boys feel the impact of only a moment?s pleasure, for the remainder of their lives.

  4. Hey, you used to write fantastic, but the last several posts have been kinda boring? I miss your great writings. Past few posts are just a little out of track! come on!

  5. Caliburn vape表示:

    hi!,I like your writing very much! share we communicate more about your article on AOL? I require an expert on this area to solve my problem. May be that’s you! Looking forward to see you.

  6. I was curious if you ever thought of changing the structure of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or two pictures. Maybe you could space it out better?

  7. Caliburn表示:

    Can I just say what a aid to search out someone who truly knows what theyre talking about on the internet. You undoubtedly know how you can carry an issue to light and make it important. Extra folks have to read this and perceive this facet of the story. I cant imagine youre not more widespread because you undoubtedly have the gift.

  8. Flum float表示:

    Your house is valueble for me. Thanks!?

  9. This really answered my problem, thanks!

  10. I am very happy to read this. This is the kind of manual that needs to be given and not the accidental misinformation that’s at the other blogs. Appreciate your sharing this best doc.

  11. Excellent beat ! I would like to apprentice even as you amend your website, how can i subscribe for a blog site? The account aided me a appropriate deal. I have been tiny bit acquainted of this your broadcast provided vibrant transparent idea

  12. Flum flavors表示:

    Thanks for the concepts you have shared here. Moreover, I believe there are several factors that keep your car insurance premium all the way down. One is, to contemplate buying automobiles that are inside the good report on car insurance companies. Cars which might be expensive tend to be at risk of being robbed. Aside from that insurance coverage is also in line with the value of your truck, so the more expensive it is, then higher a premium you have to pay.

  13. Flum flavors表示:

    I have seen plenty of useful elements on your website about computers. However, I have got the thoughts and opinions that laptops are still more or less not powerful enough to be a wise decision if you normally do projects that require many power, for instance video editing. But for web surfing, word processing, and the majority of other typical computer functions they are all right, provided you don’t mind the screen size. Many thanks for sharing your thinking.

  14. Wonderful work! This is the type of information that should be shared around the web. Shame on the search engines for not positioning this post higher! Come on over and visit my website . Thanks =)

  15. Flum flavors表示:

    One other important part is that if you are a senior citizen, travel insurance pertaining to pensioners is something that is important to really take into account. The more aged you are, greater at risk you happen to be for allowing something bad happen to you while in foreign countries. If you are never covered by some comprehensive insurance plan, you could have some serious challenges. Thanks for revealing your advice on this web blog.

  16. porno_yvEi表示:

    русское порно анал бесплатно русское порно анал бесплатно .

  17. BestHotelsBax表示:

    Great site! I recommend to everyone!Best hotels Guide with price

  18. Mthbqx表示:

    buy ascorbic acid generic – ferrous where to buy buy compro paypal

  19. Great site! I recommend to everyone!The best hotels

  20. En guvenilir kumarhanede kazan?n Sweet bonanza

  21. Help you get the most out of the services – Promonode

  22. Seveceginiz bir online casino Sweet bonanza

  23. Stevepsymn表示:

    В чёрный список пирамид и лохотронов 31 августа 2022 года внесены следующие организации, обладающие признаками финансовой пирамиды или признаками мошенничества.
    анальный секс первые
    Etihad Rail (etihadrail-ae.com)

    Club Unite To Live, Life Is Good, Unite To Live (uniteto.live). Новый домен пирамиды находящегося в розыске Романа Василенко.

    TopBoom, «платформа хедж-фонда, специализирующегося на сделках с обратным исходом спортивного события» (topboom.vip, t.me/TopBoom001)

    Change Team, мошенники указывают реквизиты чужого юрлица ООО «АТТИС ГРУПП» (ОРГН 1207700314128, ИНН 9702022065), телеграм-канал «Change Team: Главный Канал» (change-team.ru). Фальшивый обменник раньше назывался C Exchange.
    Ещё лохотроны:
    Scam! Чёрный список пирамид и лохотронов и отзывы

    В чёрный список пирамид и лохотронов включены организации, имеющие признаки финансовой пирамиды по классификации Центрального банка; организации, обладающие признаками матричной пирамиды (массовый привод друзей, «столы»); сборы денег с пенсионеров и прочих незащищённых слоёв населения; хайпы; организации, имеющие негативные отзывы; структуры, оказывающие финансовые услуги без лицензии и прочие лохотроны за исключением псевдоброкеров, кооперативов (с ними тоже не рекомендуем связываться) и некоторых других категорий.

  24. Vincenthit表示:

    В чёрный список пирамид и лохотронов 31 августа 2022 года внесены следующие организации, обладающие признаками финансовой пирамиды или признаками мошенничества.
    жесток порно видео
    Etihad Rail (etihadrail-ae.com)

    Club Unite To Live, Life Is Good, Unite To Live (uniteto.live). Новый домен пирамиды находящегося в розыске Романа Василенко.

    TopBoom, «платформа хедж-фонда, специализирующегося на сделках с обратным исходом спортивного события» (topboom.vip, t.me/TopBoom001)

    Change Team, мошенники указывают реквизиты чужого юрлица ООО «АТТИС ГРУПП» (ОРГН 1207700314128, ИНН 9702022065), телеграм-канал «Change Team: Главный Канал» (change-team.ru). Фальшивый обменник раньше назывался C Exchange.
    Ещё лохотроны:
    Scam! Чёрный список пирамид и лохотронов и отзывы

    В чёрный список пирамид и лохотронов включены организации, имеющие признаки финансовой пирамиды по классификации Центрального банка; организации, обладающие признаками матричной пирамиды (массовый привод друзей, «столы»); сборы денег с пенсионеров и прочих незащищённых слоёв населения; хайпы; организации, имеющие негативные отзывы; структуры, оказывающие финансовые услуги без лицензии и прочие лохотроны за исключением псевдоброкеров, кооперативов (с ними тоже не рекомендуем связываться) и некоторых других категорий.

  25. StephenDeery表示:

    I got this web page from my friend who informed me on the topic of this site and at the moment this time I am visiting this website and reading very informative articles at this place.

    https://frontersupport.com/the-best-clothes-remover-in-2024/

  26. Kumar oynamak icin en iyi secim Sweet bonanza

  27. En iyi kumarhanede sans?n?z? deneyin Sweet bonanza

  28. Siglrh表示:

    purchase zofran pill – buy procyclidine cheap requip 1mg brand

  29. Great site! I recommend to everyone!online hotel booking

  30. Oynamak icin harika bir kumarhane Sweet bonanza

發佈留言

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