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

15,418 Responses

  1. One more thing I would like to talk about is that as an alternative to trying to accommodate all your online degree tutorials on days that you finish work (since the majority people are exhausted when they get home), try to get most of your instructional classes on the week-ends and only a couple courses for weekdays, even if it means a little time off your weekend break. This is beneficial because on the saturdays and sundays, you will be extra rested as well as concentrated in school work. Many thanks for the different tips I have learned from your weblog.

  2. Thanks for your posting. I also feel that laptop computers have grown to be more and more popular nowadays, and now will often be the only kind of computer used in a household. The reason is that at the same time they are becoming more and more affordable, their working power keeps growing to the point where these are as strong as pc’s from just a few years ago.

  3. I’ve noticed that credit repair activity really needs to be conducted with tactics. If not, you are going to find yourself damaging your rank. In order to realize your aspirations in fixing your credit rating you have to make sure that from this moment in time you pay your complete monthly costs promptly in advance of their slated date. It is significant on the grounds that by not really accomplishing that, all other steps that you will decide on to improve your credit standing will not be efficient. Thanks for discussing your ideas.

  4. Greetings! I’ve been following your web site for a long time now and finally got the bravery to go ahead and give you a shout out from Kingwood Texas! Just wanted to say keep up the fantastic job!

  5. Thanks for sharing your ideas on this blog. Additionally, a fairy tale regarding the banking institutions intentions whenever talking about foreclosure is that the lender will not getreceive my payments. There is a specific amount of time in which the bank can take payments here and there. If you are too deep inside the hole, they may commonly require that you pay the payment in full. However, i am not saying that they will have any sort of payments at all. Should you and the lender can seem to work some thing out, the particular foreclosure procedure may halt. However, in case you continue to miss out on payments in the new approach, the home foreclosure process can just pick up from where it left off.

  6. Hi there, just turned into alert to your blog thru Google, and found that it’s really informative. I am gonna be careful for brussels. I?ll appreciate if you happen to proceed this in future. Numerous other folks can be benefited out of your writing. Cheers!

  7. Thanks a bunch for sharing this with all of us you actually know what you are talking about! Bookmarked. Please also visit my web site =). We could have a link exchange arrangement between us!

  8. Nice post. I study something more difficult on completely different blogs everyday. It’ll all the time be stimulating to learn content from other writers and follow slightly one thing from their store. I?d prefer to make use of some with the content on my weblog whether you don?t mind. Natually I?ll offer you a link in your internet blog. Thanks for sharing.

  9. Отличный сайт! Всем рекомендую!картина на холсте в Тюмени

  10. Wow! This could be one particular of the most useful blogs We have ever arrive across on this subject. Basically Wonderful. I’m also a specialist in this topic so I can understand your hard work.

  11. Fantastic beat ! I would like to apprentice while you amend your website, how could i subscribe for a blog website? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear concept

  12. I have realized that over the course of creating a relationship with real estate owners, you’ll be able to get them to understand that, in most real estate financial transaction, a payment is paid. Eventually, FSBO sellers don’t “save” the commission. Rather, they struggle to win the commission by means of doing a great agent’s task. In the process, they commit their money as well as time to accomplish, as best they will, the assignments of an realtor. Those jobs include uncovering the home by means of marketing, representing the home to prospective buyers, making a sense of buyer emergency in order to prompt an offer, booking home inspections, controlling qualification check ups with the bank, supervising maintenance, and facilitating the closing of the deal.

  13. Many thanks for this article. I will also like to state that it can end up being hard if you are in school and just starting out to create a long credit history. There are many scholars who are simply trying to endure and have a good or beneficial credit history is often a difficult issue to have.

  14. There may be noticeably a bundle to find out about this. I assume you made certain nice points in features also.

  15. Thanks for sharing excellent informations. Your site is very cool. I am impressed by the details that you have on this site. It reveals how nicely you perceive this subject. Bookmarked this website page, will come back for extra articles. You, my friend, ROCK! I found simply the info I already searched all over the place and simply could not come across. What an ideal site.

  16. I have noticed that online education is getting favorite because getting your degree online has become a popular method for many people. A huge number of people have not necessarily had a chance to attend an established college or university nevertheless seek the increased earning potential and a better job that a Bachelors Degree gives. Still other people might have a diploma in one field but would wish to pursue anything they now possess an interest in.

  17. Easydrorbix表示:

    clindamycin uk pharmacy: pharmacy support team viagra – actonel online pharmacy

  18. Easydrorbix表示:

    hydrochlorothiazide online pharmacy: overseas pharmacy cialis – crestor pharmacy online

  19. Hi my loved one! I wish to say that this article is amazing, great written and come with approximately all significant infos. I would like to see more posts like this .

  20. Thanks, I’ve been searching for information about this subject matter for ages and yours is the best I’ve discovered so far.

  21. Greetings from Idaho! I’m bored at work so I decided to check out your site on my iphone during lunch break. I really like the info you provide here and can’t wait to take a look when I get home. I’m shocked at how quick your blog loaded on my mobile .. I’m not even using WIFI, just 3G .. Anyways, very good site!

  22. Easydrorbix表示:

    Dipyridamole: order cialis online pharmacy – purchase adipex from an online pharmacy

  23. hi!,I like your writing very much! share we communicate more about your post on AOL? I require an expert on this area to solve my problem. May be that’s you! Looking forward to see you.

  24. I?m not sure where you are getting your info, but good topic. I needs to spend some time learning more or understanding more. Thanks for magnificent info I was looking for this information for my mission.

  25. eve thai表示:

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

  26. Thanks for the ideas you are sharing on this weblog. Another thing I want to say is the fact that getting hold of some copies of your credit score in order to scrutinize accuracy of any detail may be the first motion you have to accomplish in repairing credit. You are looking to clear your credit file from destructive details mistakes that mess up your credit score.

  27. These days of austerity in addition to relative panic about running into debt, lots of people balk about the idea of making use of a credit card to make acquisition of merchandise or even pay for a vacation, preferring, instead just to rely on the actual tried plus trusted method of making repayment – hard cash. However, if you possess cash there to make the purchase completely, then, paradoxically, that is the best time just to be able to use the credit cards for several reasons.

  28. There are some interesting points in time in this article however I don?t know if I see all of them middle to heart. There’s some validity however I will take maintain opinion until I look into it further. Good article , thanks and we want more! Added to FeedBurner as nicely

  29. Interesting blog post. Some tips i would like to make contributions about is that pc memory must be purchased in case your computer can no longer cope with anything you do by using it. One can mount two RAM memory boards with 1GB each, for example, but not certainly one of 1GB and one having 2GB. One should check the car maker’s documentation for own PC to ensure what type of storage is needed.

  30. It?s laborious to seek out educated folks on this subject, but you sound like you understand what you?re speaking about! Thanks

發佈留言

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