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

  1. Thanks for the ideas shared on your own blog. Something else I would like to say is that weight loss is not all about going on a fad diet and trying to get rid of as much weight as you can in a set period of time. The most effective way to shed weight is by getting it slowly but surely and following some basic suggestions which can allow you to make the most from your attempt to shed weight. You may learn and already be following these tips, however reinforcing knowledge never hurts.

  2. AlbertShund表示:

    https://olympecasino.pro/# olympe casino avis

  3. Gregoryron表示:

    olympe casino avis: olympe casino – olympe casino cresus

  4. I have read a few good stuff here. Definitely worth bookmarking for revisiting. I wonder how so much effort you place to create such a magnificent informative site.

  5. AlbertShund表示:

    https://olympecasino.pro/# casino olympe

  6. Thanks for your posting on this web site. From my experience, occasionally softening up a photograph may well provide the wedding photographer with a little bit of an imaginative flare. Sometimes however, this soft cloud isn’t precisely what you had under consideration and can quite often spoil a normally good snapshot, especially if you thinking about enlarging that.

  7. Gregoryron表示:

    olympe casino cresus: olympe casino en ligne – olympe casino

  8. porn表示:

    I have seen that good real estate agents almost everywhere are Marketing and advertising. They are recognizing that it’s more than simply placing a sign post in the front area. It’s really concerning building human relationships with these retailers who sooner or later will become buyers. So, when you give your time and effort to encouraging these vendors go it alone : the “Law regarding Reciprocity” kicks in. Interesting blog post.

  9. sex表示:

    you’re really a good webmaster. The website loading speed is amazing. It seems that you’re doing any unique trick. Furthermore, The contents are masterpiece. you’ve done a wonderful job on this topic!

  10. VictorVal表示:

    olympe casino avis: olympe casino avis – olympe casino

  11. sma bokep表示:

    An added important component is that if you are an older person, travel insurance with regard to pensioners is something you must really take into account. The mature you are, the more at risk you might be for allowing something undesirable happen to you while in another country. If you are not really covered by a few comprehensive insurance, you could have some serious problems. Thanks for expressing your advice on this web blog.

  12. Williamwhogs表示:

    casino olympe: olympe casino avis – olympe casino avis

  13. 18++表示:

    Thanks for your publication. What I want to comment on is that when you are evaluating a good online electronics retail outlet, look for a website with full information on critical indicators such as the personal privacy statement, safety details, any payment options, along with other terms plus policies. Generally take time to read the help plus FAQ areas to get a much better idea of how a shop works, what they can perform for you, and ways in which you can take full advantage of the features.

  14. VictorVal表示:

    olympe: casino olympe – olympe

  15. AlbertShund表示:

    https://olympecasino.pro/# olympe casino avis

  16. Gregoryron表示:

    casino olympe: casino olympe – olympe

  17. sex表示:

    Hi! Would you mind if I share your blog with my zynga group? There’s a lot of people that I think would really appreciate your content. Please let me know. Cheers

  18. AlbertShund表示:

    https://olympecasino.pro/# olympe casino en ligne

  19. Gregoryron表示:

    olympe: olympe casino cresus – olympe

  20. sex表示:

    That is very interesting, You are a very professional blogger. I’ve joined your rss feed and stay up for searching for more of your excellent post. Additionally, I have shared your web site in my social networks!

  21. VictorVal表示:

    casino olympe: olympe casino – olympe casino

  22. 18++表示:

    Thanks for your useful post. Over time, I have been able to understand that the actual symptoms of mesothelioma cancer are caused by the build up connected fluid involving the lining in the lung and the chest cavity. The ailment may start inside the chest region and spread to other body parts. Other symptoms of pleural mesothelioma cancer include weight-loss, severe inhaling and exhaling trouble, fever, difficulty eating, and inflammation of the face and neck areas. It should be noted that some people existing with the disease do not experience just about any serious signs or symptoms at all.

  23. porn 18+表示:

    Howdy are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any coding expertise to make your own blog? Any help would be really appreciated!

  24. 18++表示:

    I really like your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz answer back as I’m looking to design my own blog and would like to know where u got this from. thank you

  25. VictorFaIca表示:

    Профессиональное агентство рекламное агентство Витрувий: разработка рекламы, брендинг, digital-маркетинг, наружка и SMM. Комплексное продвижение для бизнеса любого масштаба.

  26. Davidmaphy表示:

    The best online slots slot big bamboo in one place: classics, new releases, jackpots and themed machines. Play without registration, test the demo or make real bets with bonuses.

  27. sma bokep表示:

    Thanks for your publication. What I want to say is that while looking for a good on the net electronics shop, look for a internet site with total information on key elements such as the personal privacy statement, security details, any payment procedures, and also other terms plus policies. Constantly take time to look into the help and FAQ sections to get a greater idea of how the shop will work, what they are able to do for you, and in what way you can make use of the features.

  28. javporn表示:

    Normally I do not read article on blogs, but I wish to say that this write-up very pressured me to try and do so! Your writing style has been surprised me. Thank you, very great article.

  29. durvet ivermectin paste for humans ivermectin pharmacokinetics

  30. sma bokep表示:

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

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

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