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

  1. I like what you guys are up too. Such intelligent work and reporting! Keep up the excellent works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my web site 🙂

  2. One thing I’d like to reply to is that weightloss system fast is possible by the right diet and exercise. Someone’s size not simply affects appearance, but also the entire quality of life. Self-esteem, depression, health risks, as well as physical ability are damaged in putting on weight. It is possible to do everything right whilst still having a gain. Should this happen, a medical problem may be the primary cause. While a lot food and not enough workout are usually at fault, common health conditions and widely used prescriptions could greatly increase size. Thanks for your post in this article.

  3. One thing I have actually noticed is that there are plenty of misguided beliefs regarding the lenders intentions while talking about home foreclosure. One fairy tale in particular is that often the bank needs to have your house. The lending company wants your hard earned cash, not your house. They want the funds they lent you with interest. Steering clear of the bank will simply draw a new foreclosed summary. Thanks for your posting.

  4. Thanks for your short article. I would also like to say that the health insurance specialist also works best for the benefit of the actual coordinators of a group insurance plan. The health insurance broker is given a long list of benefits needed by someone or a group coordinator. What any broker may is try to find individuals or coordinators which best match those needs. Then he provides his recommendations and if both parties agree, the broker formulates binding agreement between the two parties.

  5. watermelon表示:

    Thanks for another wonderful article. Where else could anybody get that kind of info in such an ideal way of writing? I have a presentation next week, and I am on the look for such information.

  6. Do you have a spam issue on this blog; I also am a blogger, and I was wondering your situation; many of us have developed some nice procedures and we are looking to exchange methods with other folks, why not shoot me an email if interested.

  7. I believe that avoiding packaged foods is a first step to be able to lose weight. They can taste beneficial, but prepared foods contain very little vitamins and minerals, making you try to eat more simply to have enough strength to get over the day. When you are constantly ingesting these foods, switching to whole grain products and other complex carbohydrates will aid you to have more power while having less. Great blog post.

  8. I appreciate, cause I found just what I was looking for. You have ended my 4 day long hunt! God Bless you man. Have a great day. Bye

  9. That is very interesting, You’re a very skilled blogger. I’ve joined your feed and sit up for in search of more of your wonderful post. Also, I’ve shared your website in my social networks!

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

  11. I have learned new things via your blog. One other thing I’d prefer to say is newer personal computer operating systems are inclined to allow more memory to be utilized, but they furthermore demand more memory space simply to perform. If an individual’s computer is unable to handle more memory as well as newest computer software requires that storage increase, it could be the time to buy a new Laptop or computer. Thanks

  12. Thanks for any other informative website. The place else could I get that kind of info written in such a perfect manner? I have a project that I am just now operating on, and I have been on the glance out for such info.

  13. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four e-mails with the same comment. Is there any way you can remove people from that service? Appreciate it!

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

  15. I have realized that over the course of making a relationship with real estate entrepreneurs, you’ll be able to get them to understand that, in most real estate contract, a commission rate is paid. Eventually, FSBO sellers really don’t “save” the fee. Rather, they try to win the commission by simply doing a good agent’s work. In the process, they devote their money plus time to complete, as best they will, the assignments of an adviser. Those jobs include disclosing the home by means of marketing, delivering the home to willing buyers, creating a sense of buyer urgency in order to prompt an offer, arranging home inspections, managing qualification check ups with the bank, supervising maintenance tasks, and assisting the closing.

  16. I have discovered some important things through your blog post post. One other stuff I would like to state is that there are several games available on the market designed particularly for preschool age children. They contain pattern identification, colors, dogs, and shapes. These often focus on familiarization as opposed to memorization. This keeps little children engaged without sensing like they are studying. Thanks

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

  18. Another thing I’ve really noticed is that often for many people, below-average credit is the reaction to circumstances beyond their control. For example they may have been saddled with illness so that they have higher bills going to collections. It would be due to a work loss or the inability to work. Sometimes divorce proceedings can truly send the money in an opposite direction. Thanks sharing your notions on this weblog.

  19. Can I just say what a aid to search out someone who really knows what theyre talking about on the internet. You undoubtedly know methods to deliver a difficulty to mild and make it important. More folks have to learn this and understand this aspect of the story. I cant consider youre not more fashionable because you definitely have the gift.

  20. According to my observation, after a foreclosures home is marketed at a bidding, it is common with the borrower in order to still have the remaining balance on the financial loan. There are many financial institutions who try to have all service fees and liens paid off by the future buyer. Nevertheless, depending on certain programs, regulations, and state legal guidelines there may be several loans that aren’t easily handled through the switch of personal loans. Therefore, the obligation still lies on the consumer that has had his or her property in foreclosure. Thank you for sharing your ideas on this blog.

  21. You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complex and extremely broad for me. I’m looking forward for your next post, I?ll try to get the hang of it!

  22. With havin so much content and articles do you ever run into any issues of plagorism or copyright infringement? My website has a lot of unique content I’ve either created myself or outsourced but it appears a lot of it is popping it up all over the web without my authorization. Do you know any techniques to help stop content from being stolen? I’d definitely appreciate it.

  23. I don?t even know how I ended up here, but I thought this post was good. I do not know who you are but definitely you are going to a famous blogger if you are not already 😉 Cheers!

  24. I really believe that a property foreclosures can have a important effect on the debtor’s life. Property foreclosures can have a 7 to ten years negative influence on a client’s credit report. A new borrower who has applied for a mortgage or just about any loans for example, knows that the actual worse credit rating will be, the more challenging it is for any decent personal loan. In addition, it might affect a borrower’s capability to find a quality place to lease or rent, if that results in being the alternative houses solution. Good blog post.

  25. What?s Happening i’m new to this, I stumbled upon this I have discovered It absolutely helpful and it has aided me out loads. I am hoping to contribute & help other customers like its helped me. Good job.

  26. Thanks for the suggestions you are discussing on this web site. Another thing I’d really like to say is always that getting hold of copies of your credit score in order to inspect accuracy of the detail is one first activity you have to conduct in credit repair. You are looking to cleanse your credit reports from harmful details flaws that wreck your credit score.

  27. you may have an amazing blog right here! would you prefer to make some invite posts on my weblog?

  28. Thanks for these pointers. One thing I should also believe is the fact that credit cards featuring a 0 rate of interest often appeal to consumers with zero rate, instant authorization and easy on-line balance transfers, nonetheless beware of the number one factor that may void your own 0 easy road annual percentage rate and as well as throw anybody out into the terrible house in no time.

  29. Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you could do with a few pics to drive the message home a little bit, but other than that, this is magnificent blog. A fantastic read. I’ll definitely be back.

發佈留言

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