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

  1. Wow, superb blog structure! How lengthy have you ever been blogging for? you made running a blog look easy. The whole glance of your site is fantastic, as neatly as the content material!

  2. There are definitely lots of details like that to take into consideration. That is a nice point to deliver up. I supply the ideas above as normal inspiration however clearly there are questions like the one you deliver up the place crucial thing might be working in honest good faith. I don?t know if greatest practices have emerged round things like that, but I’m certain that your job is clearly identified as a good game. Each girls and boys really feel the impact of only a moment?s pleasure, for the remainder of their lives.

  3. of course like your web site but you have to take a look at the spelling on quite a few of your posts. Several of them are rife with spelling issues and I to find it very bothersome to tell the reality on the other hand I will certainly come back again.

  4. Wow! This blog looks just like my old one! It’s on a entirely different topic but it has pretty much the same layout and design. Superb choice of colors!

  5. Would you be thinking about exchanging hyperlinks?

  6. I do trust all the ideas you’ve introduced to your post. They are really convincing and can definitely work. Nonetheless, the posts are very quick for starters. Could you please extend them a bit from subsequent time? Thanks for the post.

  7. Thank you for sharing excellent informations. Your web site is very cool. I’m impressed by the details that you?ve on this blog. It reveals how nicely you understand this subject. Bookmarked this website page, will come back for extra articles. You, my friend, ROCK! I found just the information I already searched all over the place and just could not come across. What an ideal web-site.

  8. Hello would you mind stating which blog platform you’re working with? I’m going to start my own blog in the near future but I’m having a tough time making a decision between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something completely unique. P.S Sorry for being off-topic but I had to ask!

  9. Thanks for your post on the travel industry. I will also like to add that if you are one senior taking into consideration traveling, it is absolutely vital that you buy travel cover for older persons. When traveling, seniors are at biggest risk being in need of a health emergency. Getting the right insurance coverage package in your age group can look after your health and provide you with peace of mind.

  10. Good day! I know this is kinda off topic but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having problems finding one? Thanks a lot!

  11. Thanks for your publication on this site. From my very own experience, many times softening upwards a photograph may possibly provide the photo shooter with a little bit of an inspired flare. Often times however, that soft blur isn’t just what you had as the primary goal and can usually spoil a normally good photo, especially if you intend on enlarging the item.

  12. Whats up! I simply wish to give a huge thumbs up for the good data you have here on this post. I will likely be coming back to your weblog for more soon.

  13. Good write-up, I?m normal visitor of one?s blog, maintain up the nice operate, and It is going to be a regular visitor for a lengthy time.

  14. I believe one of your advertisements caused my internet browser to resize, you might want to put that on your blacklist.

  15. Thanks for giving your ideas. I’d also like to state that video games have been ever before evolving. Technology advances and revolutions have made it simpler to create genuine and fun games. These types of entertainment games were not really sensible when the actual concept was being attempted. Just like other forms of technologies, video games also have had to grow by many ages. This itself is testimony for the fast development of video games.

  16. very nice submit, i definitely love this web site, carry on it

  17. I think other web-site proprietors should take this site as an model, very clean and great user genial style and design, let alone the content. You are an expert in this topic!

  18. Thank you for another informative site. Where else could I get that type of info written in such a perfect way? I’ve a project that I am just now working on, and I have been on the look out for such info.

  19. I have noticed that car insurance companies know the cars which are susceptible to accidents along with other risks. They also know what types of cars are inclined to higher risk as well as higher risk they’ve already the higher the actual premium rate. Understanding the uncomplicated basics of car insurance just might help you choose the right kind of insurance policy that will take care of your requirements in case you become involved in an accident. Thank you sharing the actual ideas in your blog.

  20. Aw, this was a very nice post. In concept I wish to put in writing like this additionally ? taking time and precise effort to make an excellent article? however what can I say? I procrastinate alot and on no account seem to get something done.

  21. ona ona表示:

    I don?t even know the way I finished up right here, but I thought this publish was once great. I do not recognise who you are but definitely you are going to a well-known blogger should you aren’t already 😉 Cheers!

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

  23. The next time I learn a blog, I hope that it doesnt disappoint me as a lot as this one. I imply, I know it was my option to read, however I really thought youd have something attention-grabbing to say. All I hear is a bunch of whining about one thing that you can repair in the event you werent too busy in search of attention.

  24. Great blog here! Also your website loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as fast as yours lol

  25. Thanks for your post. One other thing is that individual states in the United states of america have their very own laws that will affect home owners, which makes it very, very hard for the the nation’s lawmakers to come up with the latest set of guidelines concerning foreclosures on people. The problem is that a state features own laws and regulations which may have interaction in a damaging manner in terms of foreclosure plans.

  26. I’ve come across that now, more and more people are attracted to camcorders and the area of taking pictures. However, being photographer, you have to first commit so much time frame deciding the exact model of photographic camera to buy in addition to moving store to store just so you might buy the cheapest camera of the trademark you have decided to decide on. But it won’t end just there. You also have to contemplate whether you should purchase a digital camera extended warranty. Many thanks for the good recommendations I accumulated from your weblog.

  27. Woah! I’m really loving the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between user friendliness and appearance. I must say that you’ve done a superb job with this. In addition, the blog loads extremely fast for me on Firefox. Superb Blog!

  28. One thing I’d prefer to discuss is that weight loss program fast may be possible by the suitable diet and exercise. An individual’s size not only affects appearance, but also the overall quality of life. Self-esteem, major depression, health risks, along with physical ability are afflicted in weight gain. It is possible to make everything right whilst still having a gain. If this happens, a medical problem may be the root cause. While an excessive amount of food instead of enough exercise are usually at fault, common health conditions and popular prescriptions can easily greatly increase size. Many thanks for your post in this article.

  29. A person essentially help to make seriously articles I would state. This is the very first time I frequented your web page and thus far? I surprised with the research you made to make this particular publish amazing. Fantastic job!

發佈留言

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