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

  1. It is truly a nice and helpful piece of information. I?m glad that you shared this useful info with us. Please keep us up to date like this. Thanks for sharing.

  2. Hey this is kind of of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding skills so I wanted to get advice from someone with experience. Any help would be greatly appreciated!

  3. Amazing blog! Do you have any recommendations for aspiring writers? I’m planning to start my own blog soon but I’m a little lost on everything. Would you recommend starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m totally overwhelmed .. Any suggestions? Appreciate it!

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

  5. Hello there! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us beneficial information to work on. You have done a wonderful job!

  6. Thanks for your helpful post. In recent times, I have come to be able to understand that the actual symptoms of mesothelioma cancer are caused by this build up of fluid between your lining of your lung and the chest muscles cavity. The sickness may start in the chest area and pass on to other parts of the body. Other symptoms of pleural mesothelioma include weight loss, severe inhaling trouble, nausea, difficulty eating, and inflammation of the neck and face areas. It ought to be noted that some people living with the disease will not experience any serious symptoms at all.

  7. This actually answered my drawback, thank you!

  8. I?d should verify with you here. Which isn’t one thing I often do! I get pleasure from reading a submit that may make people think. Additionally, thanks for permitting me to comment!

  9. Thanks for the something totally new you have exposed in your short article. One thing I’d like to comment on is that FSBO human relationships are built as time passes. By introducing yourself to owners the first weekend break their FSBO is usually announced, before the masses start off calling on Wednesday, you produce a good association. By sending them instruments, educational products, free reports, and forms, you become the ally. Through a personal fascination with them along with their predicament, you develop a solid network that, on many occasions, pays off as soon as the owners decide to go with a representative they know and also trust – preferably you.

  10. I think that a foreclosures can have a major effect on the debtor’s life. Real estate foreclosures can have a 7 to few years negative effects on a applicant’s credit report. A new borrower who may have applied for a mortgage or any loans even, knows that a worse credit rating is definitely, the more tough it is to get a decent loan. In addition, it may possibly affect a borrower’s chance to find a really good place to let or hire, if that results in being the alternative property solution. Good blog post.

  11. Wonderful web site. A lot of helpful information here. I?m sending it to a few pals ans also sharing in delicious. And certainly, thanks in your sweat!

  12. Thanks for the points you have shared here. Something important I would like to express is that computer memory needs generally rise along with other improvements in the technology. For instance, if new generations of processors are brought to the market, there’s usually a corresponding increase in the dimensions preferences of all computer system memory along with hard drive space. This is because software program operated through these processors will inevitably boost in power to use the new technological know-how.

  13. Admiring the dedication you put into your site and detailed information you present. It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Wonderful read! I’ve bookmarked your site and I’m including your RSS feeds to my Google account.

  14. I just couldn’t depart your website prior to suggesting that I extremely enjoyed the standard info a person provide for your visitors? Is going to be back often in order to check up on new posts

  15. ควย58表示:

    Unquestionably believe that which you stated. Your favorite reason appeared to be on the web the easiest thing to be aware of. I say to you, I certainly get irked while people think about worries that they plainly do not know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side effect , people could take a signal. Will likely be back to get more. Thanks

  16. Unquestionably imagine that which you stated. Your favourite reason seemed to be at the web the simplest factor to remember of. I say to you, I definitely get irked at the same time as other people consider worries that they just don’t recognize about. You controlled to hit the nail upon the top and also defined out the entire thing without having side effect , other people could take a signal. Will probably be again to get more. Thanks

  17. быстрый вывод из запоя в стационаре http://www.vyvod-iz-zapoya-sochi12.ru .

  18. I have been absent for some time, but now I remember why I used to love this site. Thanks , I will try and check back more frequently. How frequently you update your site?

  19. Excellent beat ! I wish to apprentice at the same time as you amend your web site, how can i subscribe for a blog site? The account aided me a applicable deal. I had been tiny bit acquainted of this your broadcast provided brilliant transparent idea

  20. okmark your blog and check again here regularly. I am quite sure I?ll learn a lot of new stuff right here! Best of luck for the next!

  21. After I initially commented I clicked the -Notify me when new feedback are added- checkbox and now each time a remark is added I get 4 emails with the same comment. Is there any manner you can take away me from that service? Thanks!

  22. I really appreciate this post. I?ve been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thanks again

  23. It is appropriate time to make some plans for the future and it’s time to be happy. I’ve read this post and if I could I wish to suggest you some interesting things or tips. Perhaps you can write next articles referring to this article. I wish to read more things about it!

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

  25. Amazing blog! Do you have any tips and hints for aspiring writers? I’m hoping to start my own site soon but I’m a little lost on everything. Would you advise starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely confused .. Any suggestions? Many thanks!

  26. Thanks for your beneficial post. As time passes, I have come to be able to understand that the symptoms of mesothelioma cancer are caused by the particular build up associated fluid between your lining on the lung and the torso cavity. The infection may start inside the chest area and get distributed to other body parts. Other symptoms of pleural mesothelioma include fat loss, severe inhaling and exhaling trouble, throwing up, difficulty ingesting, and puffiness of the neck and face areas. It ought to be noted that some people having the disease don’t experience just about any serious signs or symptoms at all.

  27. Hmm is anyone else encountering problems with the images on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog. Any responses would be greatly appreciated.

  28. Another thing I have noticed is the fact for many people, less-than-perfect credit is the consequence of circumstances over and above their control. One example is they may are already saddled with illness and because of this they have substantial bills going to collections. Maybe it’s due to a work loss or perhaps the inability to go to work. Sometimes breakup can really send the financial circumstances in the undesired direction. Many thanks sharing your notions on this site.

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

  30. One thing I’d really like to say is car insurance cancellations is a terrifying experience and if you are doing the appropriate things as a driver you may not get one. A lot of people do have the notice that they have been officially dumped by their insurance company and several have to scramble to get further insurance from a cancellation. Low cost auto insurance rates usually are hard to get after the cancellation. Having the main reasons with regard to auto insurance termination can help car owners prevent getting rid of in one of the most vital privileges offered. Thanks for the suggestions shared via your blog.

發佈留言

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