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

  1. TimothyDok表示:

    usa canada pharm usa canada pharm usa canada pharm

  2. JAVHD表示:

    fantastic issues altogether, you just gained a new reader. What might you suggest about your post that you made some days ago? Any positive?

  3. JAVHD表示:

    Hello there! I know this is kinda off topic but I was wondering if you knew where I could find a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having problems finding one? Thanks a lot!

  4. Dwightkak表示:

    USACanadaPharm: onlinecanadianpharmacy – usa canada pharm

  5. Dwightkak表示:

    usa canada pharm: legit canadian pharmacy – pharmacies in canada that ship to the us

  6. JAVHD表示:

    There’s noticeably a bundle to find out about this. I assume you made sure nice points in options also.

  7. StephenCer表示:

    usa canada pharm: cross border pharmacy canada – usa canada pharm

  8. Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is excellent, let alone the content!

  9. JAVHD表示:

    hi!,I like your writing very so much! share we be in contact extra approximately your article on AOL? I need a specialist in this area to solve my problem. Maybe that is you! Taking a look forward to peer you.

  10. TimothyDok表示:

    usa canada pharm usa canada pharm canadian pharmacy 24

  11. Albertbiave表示:

    https://usacanadapharm.shop/# buy drugs from canada

  12. Dwightkak表示:

    canadian drugstore online: USACanadaPharm – onlinepharmaciescanada com

  13. JAVHD表示:

    Its like you read my thoughts! You seem to know so much about this, such as you wrote the ebook in it or something. I feel that you can do with a few percent to pressure the message house a bit, but instead of that, that is fantastic blog. A great read. I will definitely be back.

  14. JAVHD表示:

    Right now it seems like Expression Engine is the top blogging platform out there right now. (from what I’ve read) Is that what you’re using on your blog?

  15. JAVHD表示:

    I can’t believe how amazing this article is! The author has done a phenomenal job of delivering the information in an compelling and enlightening manner. I can’t thank him enough for providing such priceless insights that have definitely enhanced my knowledge in this topic. Bravo to her for creating such a work of art!

  16. JAVHD表示:

    I have figured out some important matters through your blog post. One other thing I would like to state is that there are lots of games available on the market designed specifically for toddler age kids. They include things like pattern acknowledgement, colors, creatures, and styles. These often focus on familiarization instead of memorization. This makes little kids occupied without experiencing like they are studying. Thanks

  17. JAVHD表示:

    Hello There. I found your blog using msn. This is a really well written article. I will make sure to bookmark it and come back to read more of your useful information. Thanks for the post. I will certainly return.

  18. In these days of austerity plus relative anxiousness about having debt, many people balk up against the idea of employing a credit card to make purchase of merchandise or even pay for a vacation, preferring, instead only to rely on the particular tried along with trusted means of making repayment – hard cash. However, if you have the cash available to make the purchase 100 , then, paradoxically, that’s the best time for them to use the cards for several motives.

  19. Albertbiave表示:

    https://usacanadapharm.com/# my canadian pharmacy review

  20. JAVHD表示:

    Excellent read, I just passed this onto a friend who was doing a little research on that. And he just bought me lunch since I found it for him smile Thus let me rephrase that: Thanks for lunch!

  21. JAVHD表示:

    Normally I don’t read post on blogs, but I wish to say that this write-up very forced me to try and do it! Your writing taste has been amazed me. Thank you, very nice post.

  22. JAVHD表示:

    We stumbled over here coming from a different page and thought I might check things out. I like what I see so now i am following you. Look forward to exploring your web page repeatedly.

  23. StephenCer表示:

    usa canada pharm: canada drugs – pharmacy wholesalers canada

  24. JAVHD表示:

    I have realized that online diploma is getting common because obtaining your degree online has become a popular choice for many people. Numerous people have never had a possible opportunity to attend a normal college or university yet seek the improved earning potential and career advancement that a Bachelors Degree affords. Still other people might have a degree in one field but would choose to pursue anything they now possess an interest in.

  25. JAVHD表示:

    Another thing is that when looking for a good on the net electronics store, look for web shops that are regularly updated, keeping up-to-date with the most recent products, the perfect deals, as well as helpful information on products. This will ensure that you are getting through a shop that really stays atop the competition and gives you what you need to make educated, well-informed electronics purchases. Thanks for the essential tips I’ve learned from your blog.

  26. JAVHD表示:

    We’re a group of volunteers and opening a new scheme in our community. Your website offered us with valuable info to work on. You’ve done an impressive job and our whole community will be grateful to you.

  27. JAVHD表示:

    WONDERFUL Post.thanks for share..more wait .. ?

  28. JAVHD表示:

    I’m really loving the theme/design of your website. Do you ever run into any browser compatibility problems? A few of my blog visitors have complained about my blog not working correctly in Explorer but looks great in Chrome. Do you have any advice to help fix this problem?

  29. It is my belief that mesothelioma can be the most fatal cancer. It’s got unusual features. The more I really look at it the more I am certain it does not act like a true solid tissue cancer. In the event that mesothelioma is actually a rogue virus-like infection, so there is the possibility of developing a vaccine in addition to offering vaccination for asbestos subjected people who are at high risk of developing future asbestos linked malignancies. Thanks for giving your ideas on this important health issue.

  30. JAVHD表示:

    Nice post. I study something more difficult on totally different blogs everyday. It’s going to all the time be stimulating to read content from other writers and follow just a little one thing from their store. I?d choose to make use of some with the content material on my weblog whether you don?t mind. Natually I?ll provide you with a hyperlink on your net blog. Thanks for sharing.

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

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