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

  1. Good post. I learn something more difficult on totally different blogs everyday. It can all the time be stimulating to learn content from other writers and practice somewhat one thing from their store. I?d prefer to use some with the content on my weblog whether or not you don?t mind. Natually I?ll offer you a hyperlink on your net blog. Thanks for sharing.

  2. honeytipsy表示:

    Thanks for your article on the vacation industry. I’d personally also like contribute that if you are one senior taking into account traveling, it’s absolutely vital that you buy travel cover for retirees. When traveling, older persons are at biggest risk of getting a health-related emergency. Getting the right insurance policies package on your age group can look after your health and give you peace of mind.

  3. My developer is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using WordPress on various websites for about a year and am concerned about switching to another platform. I have heard excellent things about blogengine.net. Is there a way I can import all my wordpress content into it? Any kind of help would be really appreciated!

  4. вывод из запоя на дому ростов круглосуточно вывод из запоя на дому ростов круглосуточно .

  5. What an informative and meticulously-researched article! The author’s attention to detail and capability to present complex ideas in a comprehensible manner is truly admirable. I’m totally enthralled by the scope of knowledge showcased in this piece. Thank you, author, for offering your expertise with us. This article has been a true revelation!

  6. What?s Taking place i am new to this, I stumbled upon this I’ve found It positively helpful and it has aided me out loads. I am hoping to contribute & assist different customers like its aided me. Good job.

  7. DanielTet表示:

    Misoprostol 200 mg buy online https://furosemide.win/# lasix 100 mg tablet
    furosemide 100mg

  8. Hiya! I simply wish to give a huge thumbs up for the nice information you’ve right here on this post. I will likely be coming again to your weblog for more soon.

  9. Stanleyinolf表示:

    does tamoxifen cause bone loss Purchase Nolvadex Online nolvadex price

  10. The things i have seen in terms of laptop memory is the fact that there are specs such as SDRAM, DDR and so forth, that must go with the technical specs of the mother board. If the computer’s motherboard is fairly current and there are no os issues, improving the storage space literally requires under an hour or so. It’s one of several easiest computer system upgrade methods one can imagine. Thanks for spreading your ideas.

  11. What I have seen in terms of laptop memory is the fact that there are specs such as SDRAM, DDR and so on, that must match up the specific features of the motherboard. If the personal computer’s motherboard is very current while there are no main system issues, replacing the storage space literally requires under 1 hour. It’s among the list of easiest computer upgrade processes one can consider. Thanks for spreading your ideas.

  12. It is best to take part in a contest for among the finest blogs on the web. I’ll recommend this website!

  13. Hi there! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

  14. Do you have a spam issue on this site; I also am a blogger, and I was wondering your situation; we have created some nice practices and we are looking to exchange methods with other folks, please shoot me an e-mail if interested.

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

  16. Jamesric表示:

    brand name lipitor price: Atorvastatin 20 mg buy online – lowest price lipitor

  17. Hiya, I’m really glad I’ve found this information. Today bloggers publish only about gossips and net and this is actually annoying. A good web site with exciting content, that’s what I need. Thanks for keeping this site, I will be visiting it. Do you do newsletters? Can’t find it.

  18. Jamesric表示:

    tamoxifen cancer: nolvadex only pct – tamoxifen estrogen

  19. Jamesric表示:

    furosemide 100mg: lasix online – furosemida 40 mg

  20. I have not checked in here for some time since I thought it was getting boring, but the last several posts are great quality so I guess I?ll add you back to my everyday bloglist. You deserve it my friend 🙂

  21. certainly like your web site however you need to take a look at the spelling on quite a few of your posts. Several of them are rife with spelling problems and I to find it very troublesome to tell the reality nevertheless I?ll certainly come back again.

  22. Trefrlg表示:

    Здравствуйте!
    Быстрая схема покупки диплома старого образца: что важно знать?
    forumjizni.ru/member.php?u=121433
    Рады оказаться полезными!.

  23. Thanks a lot for sharing this with all of us you actually know what you are talking about! Bookmarked. Please also visit my site =). We could have a link exchange agreement between us!

  24. Good ? I should definitely pronounce, impressed with your site. I had no trouble navigating through all the tabs and related information ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or something, web site theme . a tones way for your customer to communicate. Excellent task..

  25. Hello, i believe that i saw you visited my site thus i got here to ?go back the desire?.I am attempting to find issues to improve my web site!I suppose its adequate to make use of some of your ideas!!

  26. I?d must check with you here. Which isn’t something I normally do! I take pleasure in studying a submit that may make individuals think. Additionally, thanks for allowing me to comment!

  27. My brother suggested I might like this web site. He was entirely right. This post truly made my day. You can not imagine simply how much time I had spent for this info! Thanks!

  28. Poker Online表示:

    Here is my blog post … Poker Online

發佈留言

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