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...

11,011 Responses

  1. Jamesric表示:

    buy cytotec online fast delivery: buy cytotec online – buy cytotec in usa

  2. My brother suggested I might like this web site. He was entirely right. This post truly made my day. You can not imagine simply how much time I had spent for this information! Thanks!

  3. One thing I want to say is the fact before purchasing more personal computer memory, have a look at the machine within which it could be installed. If the machine is actually running Windows XP, for instance, the memory threshold is 3.25GB. Installing in excess of this would basically constitute some sort of waste. Make sure that one’s motherboard can handle the upgrade amount, as well. Good blog post.

  4. Many thanks for your post. I want to say that the price of car insurance differs a lot from one plan to another, given that there are so many different facets which play a role in the overall cost. For example, the model and make of the car will have a massive bearing on the charge. A reliable aged family motor vehicle will have a lower priced premium compared to a flashy expensive car.

  5. DanielTet表示:

    purchase cytotec https://furosemide.win/# lasix 100 mg
    lasix tablet

  6. I’m extremely impressed with your writing skills and also with the layout on your blog. Is this a paid theme or did you modify it yourself? Anyway keep up the nice quality writing, it is rare to see a nice blog like this one nowadays..

  7. Thanks for the interesting things you have disclosed in your post. One thing I’d prefer to comment on is that FSBO associations are built eventually. By releasing yourself to the owners the first saturday and sunday their FSBO is definitely announced, prior to a masses begin calling on Friday, you build a good interconnection. By sending them resources, educational components, free accounts, and forms, you become an ally. Through a personal affinity for them in addition to their predicament, you generate a solid network that, in many cases, pays off in the event the owners decide to go with a realtor they know as well as trust – preferably you actually.

  8. DanielTet表示:

    buy cytotec online fast delivery https://cytotec.pro/# cytotec pills buy online
    lasix 40mg

  9. Owning a private home has benefits that definitely make the family life more befitting and comfortable.

  10. One important issue is that when you find yourself searching for a student loan you may find that you’ll want a co-signer. There are many situations where this is true because you may find that you do not possess a past credit rating so the mortgage lender will require that you have someone cosign the borrowed funds for you. Great post.

  11. I know of the fact that today, more and more people are attracted to digital cameras and the industry of photography. However, as a photographer, you must first commit so much time frame deciding which model of digicam to buy as well as moving store to store just so you could possibly buy the least expensive camera of the trademark you have decided to decide on. But it will not end at this time there. You also have to contemplate whether you should purchase a digital dslr camera extended warranty. Thanks for the good recommendations I received from your weblog.

  12. Another issue is that video gaming has become one of the all-time most important forms of entertainment for people of all ages. Kids participate in video games, and adults do, too. The actual XBox 360 is among the favorite games systems for people who love to have hundreds of activities available to them, as well as who like to learn live with people all over the world. Thanks for sharing your opinions.

  13. I really like your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to construct my own blog and would like to find out where u got this from. thanks

  14. This blog does not show up properly on my android – you may wanna try and repair that

  15. Many thanks for your post. I’d really like to say that the cost of car insurance varies widely from one insurance policy to another, since there are so many different issues which give rise to the overall cost. By way of example, the make and model of the car will have an enormous bearing on the cost. A reliable old family motor vehicle will have a lower priced premium over a flashy racecar.

  16. I?ve learn several just right stuff here. Certainly worth bookmarking for revisiting. I surprise how much attempt you put to create one of these fantastic informative site.

  17. I am typically to blogging and i actually admire your content. The article has really peaks my interest. I am going to bookmark your website and keep checking for brand spanking new information.

  18. I am not sure where you are getting your information, but great topic. I needs to spend some time learning much more or understanding more. Thanks for excellent information I was looking for this info for my mission.

  19. I was wondering if you ever thought of changing the page layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or two pictures. Maybe you could space it out better?

  20. Audio began playing any time I opened up this web site, so annoying!

  21. Hey there, I think your website might be having browser compatibility issues. When I look at your website in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, terrific blog!

  22. I am no longer sure where you are getting your information, however great topic. I needs to spend a while finding out more or understanding more. Thanks for great information I used to be on the lookout for this information for my mission.

  23. Oh my goodness! an incredible article dude. Thanks Nevertheless I am experiencing problem with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting similar rss drawback? Anyone who is aware of kindly respond. Thnkx

  24. I would like to add if you do not already have got an insurance policy or maybe you do not form part of any group insurance, you could possibly well gain from seeking the help of a health insurance agent. Self-employed or those with medical conditions normally seek the help of the health insurance agent. Thanks for your short article.

  25. revenge 2023表示:

    I have really learned some new things as a result of your site. One other thing I would really like to say is that newer computer operating systems often allow more memory to use, but they in addition demand more storage simply to work. If your computer is not able to handle much more memory as well as newest software requires that ram increase, it might be the time to shop for a new Laptop. Thanks

  26. Anyone who has been a prey to speculation fraud should contact an Investment Lawyer as soon as possible for dragging the culprits behind bars.

  27. Thanks a lot for sharing this with all people you really understand what you’re talking about! Bookmarked. Kindly also discuss with my site =). We will have a link trade agreement between us!

  28. 2023表示:

    I have noticed that wise real estate agents all over the place are Advertising. They are seeing that it’s more than merely placing a sign post in the front area. It’s really regarding building interactions with these sellers who at some point will become customers. So, after you give your time and effort to encouraging these traders go it alone — the “Law associated with Reciprocity” kicks in. Interesting blog post.

發佈留言

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