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

  1. I have been exploring for a bit for any high-quality articles or weblog posts in this kind of house . Exploring in Yahoo I at last stumbled upon this web site. Studying this info So i?m satisfied to exhibit that I have a very excellent uncanny feeling I came upon exactly what I needed. I most no doubt will make certain to do not overlook this website and give it a look regularly.

  2. Hello! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Fairly certain he will have a good read. Thanks for sharing!

  3. I do agree with all of the ideas you’ve presented in your post. They are really convincing and will definitely work. Still, the posts are very short for novices. Could you please extend them a bit from next time? Thanks for the post.

  4. I like what you guys are up too. Such intelligent work and reporting! Carry on the excellent works guys I?ve incorporated you guys to my blogroll. I think it’ll improve the value of my site 🙂

  5. Something more important is that while searching for a good internet electronics shop, look for online stores that are regularly updated, preserving up-to-date with the most current products, the perfect deals, as well as helpful information on products and services. This will make sure that you are doing business with a shop which stays atop the competition and provides you what you should need to make educated, well-informed electronics buys. Thanks for the significant tips I have really learned through the blog.

  6. Wow, incredible blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is excellent, as well as the content!

  7. I’m amazed by the quality of this content! The author has clearly put a great amount of effort into exploring and organizing the information. It’s exciting to come across an article that not only provides useful information but also keeps the readers hooked from start to finish. Kudos to him for creating such a remarkable piece!

  8. Hello my loved one! I want to say that this post is awesome, nice written and include almost all significant infos. I?d like to see extra posts like this .

  9. Exceptional post but I was wondering if you could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit more. Bless you!

  10. Excellent site you have here but I was curious about if you knew of any message boards that cover the same topics talked about in this article? I’d really like to be a part of community where I can get advice from other knowledgeable individuals that share the same interest. If you have any suggestions, please let me know. Thanks a lot!

  11. I believe that avoiding highly processed foods would be the first step to be able to lose weight. They will taste fine, but refined foods possess very little vitamins and minerals, making you take more in order to have enough vigor to get with the day. Should you be constantly eating these foods, changing to whole grain products and other complex carbohydrates will aid you to have more energy while having less. Great blog post.

  12. I have realized that online diploma is getting favorite because obtaining your college degree online has developed into popular solution for many people. A large number of people have definitely not had a chance to attend a traditional college or university although seek the elevated earning potential and career advancement that a Bachelor Degree gives. Still other people might have a college degree in one training but would like to pursue one thing they now develop an interest in.

  13. I’m in awe of the author’s ability to make complex concepts approachable to readers of all backgrounds. This article is a testament to his expertise and dedication to providing helpful insights. Thank you, author, for creating such an compelling and insightful piece. It has been an incredible joy to read!

  14. The U.S. federal government offers tax credit of as much as about $3,000, relying on the automobile and date of buy.

  15. Thanks for the suggestions shared on your own blog. One more thing I would like to convey is that fat reduction is not all about going on a celebrity diet and trying to lose as much weight as possible in a few days. The most effective way to shed weight is by getting it slowly but surely and right after some basic ideas which can help you to make the most from the attempt to shed weight. You may learn and be following a few of these tips, nonetheless reinforcing know-how never hurts.

  16. Via my examination, shopping for electronic devices online can for sure be expensive, although there are some how-to’s that you can use to acquire the best offers. There are constantly ways to discover discount discounts that could make one to possess the best technology products at the smallest prices. Great blog post.

  17. Thanks for some other informative web site. The place else may I get that kind of information written in such an ideal way? I’ve a undertaking that I am just now operating on, and I’ve been at the glance out for such information.

  18. Thanks for these tips. One thing I additionally believe is the fact credit cards giving a 0 interest often lure consumers along with zero rate of interest, instant acceptance and easy on the net balance transfers, nevertheless beware of the number one factor that can void your 0 easy road annual percentage rate as well as throw one out into the bad house quickly.

  19. In the awesome scheme of things you get a B- just for effort. Exactly where you lost everybody was in your particulars. As they say, details make or break the argument.. And that couldn’t be much more accurate in this article. Having said that, let me tell you precisely what did deliver the results. The authoring is rather persuasive and this is probably why I am taking the effort to opine. I do not make it a regular habit of doing that. Second, while I can see a jumps in reasoning you make, I am definitely not convinced of how you seem to connect the points that produce the actual final result. For now I will subscribe to your issue however wish in the future you connect your facts better.

  20. I’m not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back later. Many thanks

  21. Hey very cool website!! Man .. Excellent .. Amazing .. I will bookmark your site and take the feeds also?I am happy to find a lot of useful information here in the post, we need work out more techniques in this regard, thanks for sharing. . . . . .

  22. It?s arduous to seek out educated individuals on this subject, but you sound like you know what you?re talking about! Thanks

  23. I’ve been browsing on-line greater than 3 hours as of late, yet I never discovered any fascinating article like yours. It?s beautiful value sufficient for me. In my opinion, if all site owners and bloggers made excellent content as you did, the internet will likely be a lot more helpful than ever before.

  24. It is really a nice and helpful piece of information. I am glad that you shared this helpful information with us. Please keep us up to date like this. Thank you for sharing.

  25. This will be a great website, could you be interested in doing an interview about how you designed it? If so e-mail me!

  26. Thanks for expressing your ideas. One thing is that college students have a solution between government student loan plus a private education loan where it truly is easier to opt for student loan debt consolidation reduction than through the federal student loan.

  27. Usually I do not learn article on blogs, but I wish to say that this write-up very forced me to take a look at and do it! Your writing style has been surprised me. Thank you, quite nice article.

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

  29. Hello there, You’ve done an excellent job. I?ll definitely digg it and personally recommend to my friends. I am sure they will be benefited from this web site.

  30. Excellent blog here! Also your web site quite a bit up very fast! What web host are you the use of? Can I get your affiliate link on your host? I want my site loaded up as quickly as yours lol

發佈留言

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