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

  1. Terrific work! This is the type of information that should be shared around the internet. Shame on Google for not positioning this post higher! Come on over and visit my website . Thanks =)

  2. Descubra o melhor cassino online Blaze

  3. RWC Melbourne表示:

    Hi my friend! I wish to say that this post is awesome, nice written and include almost all vital infos. I?d like to see more posts like this.

  4. Hmm it looks like your blog ate my first comment (it was extremely long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog blogger but I’m still new to everything. Do you have any suggestions for beginner blog writers? I’d genuinely appreciate it.

  5. Do you mind if I quote a few of your posts as long as I provide credit and sources back to your webpage? My blog is in the very same niche as yours and my visitors would truly benefit from a lot of the information you present here. Please let me know if this okay with you. Regards!

  6. Fantastic blog you have here but I was wondering if you knew of any forums that cover the same topics talked about here? I’d really love to be a part of online community where I can get opinions from other knowledgeable people that share the same interest. If you have any suggestions, please let me know. Bless you!

  7. Do you mind if I quote a few of your articles as long as I provide credit and sources back to your weblog? My website is in the very same area of interest as yours and my visitors would truly benefit from some of the information you present here. Please let me know if this okay with you. Cheers!

  8. Thanks for giving your ideas on this blog. As well, a fable regarding the banking institutions intentions when talking about home foreclosure is that the bank will not have my repayments. There is a fair bit of time in which the bank will require payments every now and then. If you are too deep within the hole, they are going to commonly demand that you pay that payment completely. However, i am not saying that they will not take any sort of repayments at all. In case you and the standard bank can find a way to work something out, the particular foreclosure course of action may cease. However, if you ever continue to miss payments beneath new approach, the property foreclosures process can pick up where it left off.

  9. Thanks for the tips you are giving on this website. Another thing I would like to say is always that getting hold of copies of your credit score in order to examine accuracy of each and every detail is the first action you have to execute in fixing credit. You are looking to cleanse your credit file from detrimental details faults that wreck your credit score.

  10. I’m not that much of a online reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come back in the future. Cheers

  11. It’s genuinely very complex in this full of activity
    life to listen news on Television, thus I just use world wide web for
    that reason, and take the latest news.

  12. Melhor casa de apostas para jogos de cassino Blaze

  13. Thank you for this article. I would also like to convey that it can possibly be hard when you’re in school and just starting out to initiate a long credit ranking. There are many individuals who are simply just trying to pull through and have an extended or positive credit history can be a difficult factor to have.

  14. Sua diversao garantida no nosso cassino Blaze

  15. whoah this blog is great i love studying your posts. Keep up the good work! You understand, many persons are hunting around for this information, you could aid them greatly.

  16. We will help you get the most out of your services – Promonode

  17. One important thing is that when you find yourself searching for a education loan you may find that you’ll want a cosigner. There are many situations where this is correct because you might find that you do not employ a past credit history so the lender will require that you have someone cosign the credit for you. Good post.

  18. Something else is that while searching for a good on the net electronics retail outlet, look for web shops that are continuously updated, preserving up-to-date with the most current products, the most beneficial deals, and also helpful information on services and products. This will ensure that you are dealing with a shop that stays atop the competition and provides you what you need to make intelligent, well-informed electronics buying. Thanks for the significant tips I have really learned through your blog.

  19. I have noticed that car insurance organizations know the vehicles which are vulnerable to accidents along with risks. In addition they know what sort of cars are given to higher risk along with the higher risk they may have the higher the actual premium charge. Understanding the very simple basics associated with car insurance will allow you to choose the right kind of insurance policy that should take care of the needs you have in case you become involved in an accident. Many thanks for sharing the ideas for your blog.

  20. I?ve read several good stuff here. Definitely worth bookmarking for revisiting. I wonder how much effort you put to make such a great informative site.

  21. Excellent blog here! Additionally your web site loads up very fast! What web host are you the use of? Can I am getting your affiliate link for your host? I wish my site loaded up as quickly as yours lol

  22. I can’t express how much I value the effort the author has put into producing this remarkable piece of content. The clarity of the writing, the depth of analysis, and the abundance of information offered are simply astonishing. Her zeal for the subject is obvious, and it has definitely resonated with me. Thank you, author, for sharing your insights and enlightening our lives with this incredible article!

  23. Eu recomendo um cassino confiavel Blaze

  24. I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a developer to create your theme? Fantastic work!

  25. I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a developer to create your theme? Outstanding work!

  26. Cassino com os maiores jackpots Blaze

  27. Its like you read my thoughts! You appear to grasp a lot approximately this, such as you wrote the e-book in it or something. I believe that you could do with some percent to power the message home a bit, but instead of that, this is wonderful blog. An excellent read. I will certainly be back.

  28. Thank you, I’ve been hunting for details about this topic for ages and yours is the best I’ve located so far.

發佈留言

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