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

  1. Ylvhzz表示:

    bactrim 960mg uk – cotrimoxazole price order tobrex 10mg

  2. Jkvgok表示:

    eukroma oral – buy generic desogestrel dydrogesterone 10mg usa

  3. pinterest表示:

    We are a group of volunteers and starting a new scheme in our community. Your site offered us with useful information to work on. You’ve performed an impressive task and our whole community might be thankful to you.

  4. best product表示:

    Hey! I simply would like to give an enormous thumbs up for the nice data you could have right here on this post. I might be coming again to your weblog for more soon.

  5. Hey! Would you mind if I share your blog with my facebook group? There’s a lot of folks that I think would really appreciate your content. Please let me know. Thank you

  6. It?s actually a nice and helpful piece of info. I?m happy that you shared this helpful information with us. Please stay us informed like this. Thank you for sharing.

  7. Thanks for your write-up on this site. From my personal experience, periodically softening upward a photograph may well provide the photography with a chunk of an artistic flare. More often than not however, the soft blur isn’t precisely what you had under consideration and can frequently spoil a normally good photo, especially if you anticipate enlarging them.

  8. GichardPheve表示:

    What a data of un-ambiguity and preserveness of precious experience about unpredicted emotions.

    financetimenews.ru/page/14/В 
    medik-look.ru/kupit-diplom-onlayn-udobno-i-byistroВ 
    programasites.com.br/blog/post/11666/e-mail-marketing-boas-praticas-e-temas-para-abordarВ 
    cn-agent.com/c_feedback/index.asp?page=10В 
    alcado.com.vn/san-pham-xa-hangВ 

  9. O lugar perfeito para jogar jogos de cassino Blaze

  10. Nice read, I just passed this onto a friend who was doing some research on that. And he actually bought me lunch since I found it for him smile Thus let me rephrase that: Thank you for lunch!

  11. Seu cassino online favorito Blaze

  12. Fantastic post however I was wanting to know if you could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit further. Thanks!

  13. Eu recomendo o cassino mais popular Blaze

  14. Good website! I truly love how it is simple on my eyes and the data are well written. I am wondering how I might be notified whenever a new post has been made. I have subscribed to your RSS feed which must do the trick! Have a nice day!

  15. Jogue com prazer neste cassino Blaze

  16. blog表示:

    I can’t express how much I admire the effort the author has put into creating this outstanding piece of content. The clarity of the writing, the depth of analysis, and the abundance of information provided are simply impressive. Her passion for the subject is apparent, and it has undoubtedly resonated with me. Thank you, author, for providing your knowledge and enhancing our lives with this exceptional article!

  17. Lewisslund表示:

    Awesome blog you have here but I was wanting to know if you knew of any message boards that cover the same topics discussed in this article? I’d really love to be a part of group where I can get feed-back from other experienced people that share the same interest. If you have any suggestions, please let me know. Appreciate it!
    cialis 5mg reviews

  18. I have seen loads of useful items on your internet site about computers. However, I’ve the opinion that laptop computers are still not nearly powerful more than enough to be a option if you frequently do tasks that require loads of power, for example video editing and enhancing. But for internet surfing, statement processing, and many other prevalent computer work they are just fine, provided you don’t mind small screen size. Many thanks for sharing your opinions.

  19. Wonderful blog! Do you have any helpful hints for aspiring writers? I’m hoping to start my own site soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely overwhelmed .. Any ideas? Cheers!

  20. Hi there! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains. If you know of any please share. Cheers!

  21. We stumbled over here different page and thought I should check things out. I like what I see so i am just following you. Look forward to looking over your web page repeatedly.

  22. Thank you for some other informative site. Where else could I am getting that type of information written in such an ideal way? I’ve a venture that I am just now working on, and I’ve been on the glance out for such information.

  23. I just added this webpage to my google reader, great stuff. Can’t get enough!

  24. article表示:

    This webpage won’t display properly on my i phone – you might wanna try and repair that

  25. blog表示:

    Unquestionably believe that which you said. Your favorite justification appeared to be on the internet the easiest thing to be aware of. I say to you, I definitely get irked while people consider worries that they just don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks

  26. Wow! I’m in awe of the author’s writing skills and talent to convey complicated concepts in a straightforward and clear manner. This article is a true gem that merits all the applause it can get. Thank you so much, author, for offering your expertise and providing us with such a priceless treasure. I’m truly appreciative!

  27. I discovered your blog web site on google and test just a few of your early posts. Continue to maintain up the very good operate. I just extra up your RSS feed to my MSN News Reader. Searching for ahead to studying more from you later on!?

  28. Experimente o cassino mais popular Blaze

  29. Thanks for the thoughts you have contributed here. Moreover, I believe there are numerous factors which keep your car insurance premium straight down. One is, to take into account buying cars that are inside good list of car insurance organizations. Cars that are expensive are more at risk of being lost. Aside from that insurance coverage is also in accordance with the value of the car, so the more expensive it is, then the higher your premium you only pay.

發佈留言

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