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. I just added this blog to my google reader, excellent stuff. Can not get enough!

  2. One thing is the fact one of the most prevalent incentives for making use of your card is a cash-back or even rebate provision. Generally, you will get 1-5 back on various acquisitions. Depending on the cards, you may get 1 back again on most expenses, and 5 in return on purchases made on convenience stores, gas stations, grocery stores and also ‘member merchants’.

  3. There are definitely plenty of details like that to take into consideration. That may be a great point to deliver up. I provide the ideas above as common inspiration however clearly there are questions like the one you carry up where the most important factor can be working in honest good faith. I don?t know if finest practices have emerged round things like that, but I’m certain that your job is clearly identified as a good game. Both boys and girls feel the impression of just a moment?s pleasure, for the rest of their lives.

  4. I do not even know the way I finished up here, but I thought this publish was great. I do not recognise who you are but definitely you are going to a well-known blogger if you are not already 😉 Cheers!

  5. At this time it seems like Movable Type is the preferred blogging platform out there right now. (from what I’ve read) Is that what you are using on your blog?

  6. Hello, i feel that i noticed you visited my site thus i got here to ?go back the favor?.I am trying to find issues to enhance my web site!I guess its adequate to make use of some of your concepts!!

  7. This design is steller! You certainly know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Great job. I really loved what you had to say, and more than that, how you presented it. Too cool!

  8. I can’t believe how amazing this article is! The author has done a phenomenal job of presenting the information in an compelling and informative manner. I can’t thank her enough for offering such priceless insights that have undoubtedly enhanced my knowledge in this subject area. Hats off to him for producing such a masterpiece!

  9. KevinSounc表示:

    https://sweetbonanza.network/# sweet bonanza demo oyna

  10. Fantastic blog! Do you have any hints for aspiring writers? I’m planning to start my own blog soon but I’m a little lost on everything. Would you propose starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely confused .. Any recommendations? Kudos!

  11. hi!,I like your writing very much! percentage we keep up a correspondence extra about your post on AOL? I require an expert in this house to solve my problem. Maybe that’s you! Looking forward to look you.

  12. Heya! I just wanted to ask if you ever have any issues with hackers? My last blog (wordpress) was hacked and I ended up losing several weeks of hard work due to no back up. Do you have any methods to prevent hackers?

  13. Heya i am for the first time here. I came across this board and I to find It truly useful & it helped me out much. I am hoping to give one thing again and help others like you helped me.

  14. Wow, superb blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is magnificent, let alone the content!

  15. What an insightful and well-researched article! The author’s meticulousness and capability to present complicated ideas in a comprehensible manner is truly praiseworthy. I’m thoroughly captivated by the scope of knowledge showcased in this piece. Thank you, author, for sharing your wisdom with us. This article has been a game-changer!

  16. I’ve learned new things via your website. One other thing I’d prefer to say is that often newer laptop os’s tend to allow additional memory to use, but they additionally demand more memory space simply to operate. If a person’s computer can not handle far more memory and the newest software program requires that memory increase, it may be the time to buy a new Laptop or computer. Thanks

  17. I?ve recently started a web site, the information you provide on this site has helped me tremendously. Thanks for all of your time & work.

  18. KevinSounc表示:

    http://sweetbonanza.network/# sweet bonanza guncel

  19. One other important area is that if you are an elderly person, travel insurance intended for pensioners is something you need to really take into account. The mature you are, a lot more at risk you will be for allowing something poor happen to you while abroad. If you are not really covered by quite a few comprehensive insurance policies, you could have several serious challenges. Thanks for expressing your ideas on this blog.

  20. Hello are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and create my own. Do you need any html coding knowledge to make your own blog? Any help would be really appreciated!

  21. Greetings from Ohio! I’m bored to tears at work so I decided to browse your site on my iphone during lunch break. I love the information you present here and can’t wait to take a look when I get home. I’m shocked at how quick your blog loaded on my cell phone .. I’m not even using WIFI, just 3G .. Anyhow, very good site!

  22. I’m amazed by the quality of this content! The author has undoubtedly put a tremendous amount of effort into researching and arranging the information. It’s exciting to come across an article that not only offers helpful information but also keeps the readers engaged from start to finish. Great job to him for producing such a brilliant work!

  23. baibaifern表示:

    Thanks for your post made here. One thing I would like to say is the fact that most professional job areas consider the Bachelors Degree as the entry level standard for an online college diploma. Even though Associate Certifications are a great way to get started, completing your own Bachelors reveals many good opportunities to various professions, there are numerous on-line Bachelor Course Programs available by institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another concern is that many brick and mortar institutions give Online variations of their college diplomas but often for a substantially higher cost than the corporations that specialize in online course plans.

  24. Feel free to surf to my web blog … Daycare Near Me By State

  25. certainly like your web site but you have to check the spelling on several of your posts. Several of them are rife with spelling problems and I find it very troublesome to tell the truth nevertheless I?ll definitely come back again.

  26. Woah! I’m really digging the template/theme of this blog. It’s simple, yet effective. A lot of times it’s very difficult to get that “perfect balance” between superb usability and visual appearance. I must say you have done a awesome job with this. Additionally, the blog loads extremely quick for me on Opera. Excellent Blog!

  27. Wow that was unusual. I just wrote an very long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say wonderful blog!

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

  29. Thank you for sharing all these wonderful content. In addition, the right travel along with medical insurance program can often reduce those fears that come with journeying abroad. A medical crisis can shortly become too expensive and that’s guaranteed to quickly place a financial load on the family’s finances. Having in place the great travel insurance program prior to setting off is definitely worth the time and effort. Thanks

發佈留言

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