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

  1. thca flower表示:

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

  2. I relish, result in I found just what I used to be taking a look for. You’ve ended my four day lengthy hunt! God Bless you man. Have a nice day. Bye

  3. scatterwim表示:

    You can definitely see your enthusiasm in the work you write. The world hopes for even more passionate writers like you who are not afraid to say how they believe. Always follow your heart.

  4. ремонт стиральных машин в москве адреса http://www.centr-remonta-stiralnyh-mashin.ru .

  5. Henrylip表示:

    mexican pharmaceuticals online: cmqpharma.com – mexican online pharmacies prescription drugs

  6. thca flower表示:

    I would love to add when you do not actually have an insurance policy or you do not form part of any group insurance, you could possibly well benefit from seeking the help of a health insurance broker. Self-employed or those with medical conditions generally seek the help of a health insurance specialist. Thanks for your article.

  7. MichaelPayof表示:

    mexican border pharmacies shipping to usa
    https://cmqpharma.com/# mexico pharmacies prescription drugs
    purple pharmacy mexico price list

  8. MichaelPayof表示:

    reputable mexican pharmacies online
    http://cmqpharma.com/# best online pharmacies in mexico
    buying from online mexican pharmacy

  9. Caliburn g2表示:

    I just couldn’t go away your site before suggesting that I actually loved the standard info an individual provide for your visitors? Is going to be again continuously in order to inspect new posts

  10. Caliburn vape表示:

    I’m really enjoying the theme/design of your site. Do you ever run into any web browser compatibility issues? A couple of my blog visitors have complained about my website not working correctly in Explorer but looks great in Safari. Do you have any solutions to help fix this issue?

  11. Отличный сатй! Всем рекомендую!скупка золота

  12. certainly like your web site but you need to check the spelling on quite a few of your posts. Several of them are rife with spelling problems and I in finding it very troublesome to inform the truth then again I?ll surely come back again.

  13. Hayallerinizdeki kumarhane Sweet bonanza

  14. Caliburn vape表示:

    Good ? I should certainly pronounce, impressed with your site. I had no trouble navigating through all tabs as well as related info 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 anything, web site theme . a tones way for your client to communicate. Nice task..

  15. What i don’t understood is in truth how you’re no longer really much more neatly-favored than you may be right now. You’re very intelligent. You know therefore considerably in the case of this matter, made me in my view consider it from a lot of numerous angles. Its like women and men don’t seem to be involved until it is something to do with Woman gaga! Your own stuffs excellent. All the time deal with it up!

  16. Caliburn vape表示:

    I have observed that in the world of today, video games will be the latest phenomenon with kids of all ages. Often times it may be difficult to drag the kids away from the games. If you want the very best of both worlds, there are numerous educational activities for kids. Great post.

  17. H?zl? odeme yapan kumarhane Sweet bonanza

  18. thca flower表示:

    Valuable information. Lucky me I found your web site by accident, and I am shocked why this accident didn’t happened earlier! I bookmarked it.

  19. Caliburn表示:

    I’m usually to blogging and i really admire your content. The article has really peaks my interest. I’m going to bookmark your web site and keep checking for brand spanking new information.

  20. Caliburn g2表示:

    Awesome site you have here but I was curious 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 community where I can get comments from other experienced people that share the same interest. If you have any recommendations, please let me know. Bless you!

  21. Caliburn表示:

    It’s my opinion that a property foreclosures can have a major effect on the client’s life. Property foreclosures can have a 6 to decade negative influence on a client’s credit report. A borrower who’s applied for a home loan or virtually any loans for example, knows that the particular worse credit rating is definitely, the more tough it is to acquire a decent mortgage. In addition, it could possibly affect the borrower’s power to find a really good place to let or rent, if that results in being the alternative houses solution. Thanks for your blog post.

  22. Caliburn表示:

    Thanks a bunch for sharing this with all people you really realize what you are talking approximately! Bookmarked. Please also visit my website =). We can have a hyperlink exchange contract among us!

  23. thca flower表示:

    Thanks for the strategies you share through this web site. In addition, many young women exactly who become pregnant usually do not even try to get medical health insurance because they have anxiety they wouldn’t qualify. Although some states currently require that insurers offer coverage no matter the pre-existing conditions. Fees on these kind of guaranteed options are usually higher, but when taking into consideration the high cost of medical care bills it may be the safer route to take to protect the financial future.

  24. Caliburn表示:

    Thanks for your post on the traveling industry. I might also like to include that if you are one senior thinking about traveling, it can be absolutely imperative that you buy traveling insurance for senior citizens. When traveling, elderly people are at biggest risk of experiencing a health-related emergency. Obtaining right insurance policies package on your age group can look after your health and provide you with peace of mind.

  25. thca flower表示:

    This website online is really a walk-by means of for all of the data you wished about this and didn?t know who to ask. Glimpse here, and you?ll positively discover it.

  26. thca flower表示:

    I’m not sure exactly why but this blog is loading extremely slow for me. Is anyone else having this issue or is it a issue on my end? I’ll check back later on and see if the problem still exists.

  27. thca flower表示:

    What an insightful and thoroughly-researched article! The author’s meticulousness and capability to present intricate ideas in a digestible manner is truly praiseworthy. I’m totally impressed by the breadth of knowledge showcased in this piece. Thank you, author, for offering your knowledge with us. This article has been a true revelation!

  28. thca flower表示:

    There may be noticeably a bundle to find out about this. I assume you made sure nice factors in features also.

  29. Caliburn g2表示:

    Hello, I think your website might be having browser compatibility issues. When I look at your blog in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, fantastic blog!

  30. Qmfols表示:

    durex gel buy online – durex condoms online purchase buy zovirax online cheap

發佈留言

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