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

11,141 Responses

  1. I have realized that in digital cameras, extraordinary devices help to {focus|concentrate|maintain focus|target|a**** automatically. Those kind of sensors of some digital cameras change in contrast, while others make use of a beam of infra-red (IR) light, specifically in low light. Higher specification cameras often use a mixture of both devices and may have Face Priority AF where the camera can ‘See’ any face and concentrate only upon that. Thank you for sharing your opinions on this site.

  2. It?s really a nice and helpful piece of info. I am glad that you shared this useful information with us. Please keep us up to date like this. Thanks for sharing.

  3. I?ve recently started a website, the info you provide on this web site has helped me greatly. Thank you for all of your time & work.

  4. Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but instead of that, this is magnificent blog. An excellent read. I will definitely be back.

  5. What?s Happening i am new to this, I stumbled upon this I have found It absolutely helpful and it has helped me out loads. I hope to contribute & aid other users like its helped me. Good job.

  6. Stephenzek表示:

    https://tamoxifen.bid/# nolvadex pills

  7. Stephenzek表示:

    http://lipitor.guru/# generic lipitor 20 mg

  8. Jamesric表示:

    lasix 100mg: buy furosemide – lasix 100 mg tablet

  9. Jamesric表示:

    buy misoprostol over the counter: buy cytotec online – purchase cytotec

  10. Hi, i feel that i noticed you visited my website so i came to ?go back the want?.I’m attempting to in finding issues to improve my website!I assume its ok to make use of a few of your ideas!!

  11. Jamesric表示:

    buy lipitor cheap: buy atorvastatin online – lipitor medication

  12. WilliamDeeli表示:

    Привет!
    Мы изготавливаем дипломы.
    freelance.habr.com/freelancers/ruhfhshj

  13. DanielTet表示:

    buy cytotec pills https://lisinopril.guru/# cheapest price for lisinopril
    lasix dosage

  14. Thanks for your article. What I want to say is that when searching for a good on-line electronics go shopping, look for a web page with comprehensive information on critical factors such as the privacy statement, safety details, payment procedures, and other terms plus policies. Generally take time to investigate the help along with FAQ pieces to get a better idea of how the shop performs, what they are capable of doing for you, and ways in which you can maximize the features.

  15. Hello there, You have done an incredible job. I will certainly digg it and in my view suggest to my friends. I am sure they will be benefited from this site.

  16. I like the valuable info you provide in your articles. I?ll bookmark your weblog and check again here regularly. I’m quite certain I?ll learn many new stuff right here! Best of luck for the next!

  17. DanielTet表示:

    purchase cytotec https://cytotec.pro/# purchase cytotec
    furosemide 40mg

  18. Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but instead of that, this is excellent blog. A great read. I’ll certainly be back.

  19. One thing I’ve noticed is always that there are plenty of misconceptions regarding the banking institutions intentions when talking about foreclosure. One fairy tale in particular is the fact that the bank wishes to have your house. The bank wants your hard earned dollars, not your home. They want the funds they loaned you having interest. Steering clear of the bank will draw a new foreclosed summary. Thanks for your posting.

  20. Poker Game表示:

    Also visit my web blog Poker Game

  21. I can’t express how much I appreciate the effort the author has put into producing this remarkable piece of content. The clarity of the writing, the depth of analysis, and the plethora of information offered are simply impressive. Her zeal for the subject is apparent, and it has definitely struck a chord with me. Thank you, author, for providing your knowledge and enhancing our lives with this incredible article!

  22. I like the valuable information you provide in your articles. I?ll bookmark your blog and check again here regularly. I’m quite sure I?ll learn many new stuff right here! Good luck for the next!

  23. Excellent post. I was checking continuously this blog and I am impressed! Extremely useful information particularly the last part 🙂 I care for such information much. I was seeking this particular info for a very long time. Thank you and best of luck.

  24. Stephenzek表示:

    https://lipitor.guru/# cheap lipitor

  25. Thank you, I’ve just been looking for info about this topic for ages and yours is the best I’ve discovered so far. But, what about the conclusion? Are you sure about the source?

  26. Aw, this was a very nice post. In thought I would like to put in writing like this moreover ? taking time and precise effort to make a very good article? but what can I say? I procrastinate alot and on no account seem to get one thing done.

  27. Stanleyinolf表示:

    lasix generic name furosemide online furosemide 100mg

  28. Your place is valueble for me. Thanks!?

  29. A further issue is that video games are normally serious naturally with the most important focus on mastering rather than enjoyment. Although, it has an entertainment factor to keep your children engaged, just about every game is normally designed to focus on a specific set of skills or program, such as math or technology. Thanks for your post.

發佈留言

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