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

  1. It?s really a nice and helpful piece of information. I?m happy that you simply shared this helpful info with us. Please keep us up to date like this. Thank you for sharing.

  2. I would also love to add that when you do not already have got an insurance policy or you do not form part of any group insurance, you will well reap the benefits of seeking the assistance of a health broker. Self-employed or people with medical conditions usually seek the help of an health insurance agent. Thanks for your short article.

  3. Along with the whole thing that seems to be building throughout this specific area, many of your perspectives are actually rather exciting. Having said that, I appologize, because I can not subscribe to your entire strategy, all be it exhilarating none the less. It seems to us that your comments are generally not completely rationalized and in reality you are generally your self not fully confident of your argument. In any case I did take pleasure in examining it.

  4. ฮายolf表示:

    Today, with all the fast way of life that everyone leads, credit cards have a big demand throughout the economy. Persons throughout every field are using the credit card and people who aren’t using the card have made arrangements to apply for one. Thanks for spreading your ideas about credit cards.

  5. Normally I do not learn article on blogs, however I wish to say that this write-up very compelled me to try and do so! Your writing style has been amazed me. Thanks, quite nice post.

  6. I just added this web site to my google reader, great stuff. Can not get enough!

  7. Thanks for your text. I would also like to say a health insurance brokerage service also works for the benefit of the actual coordinators of your group insurance plan. The health broker is given a directory of benefits sought by someone or a group coordinator. What any broker will is hunt for individuals or coordinators which best complement those needs. Then he shows his referrals and if both parties agree, the actual broker formulates legal contract between the two parties.

  8. you are really a good webmaster. The web site loading speed is incredible. It seems that you are doing any unique trick. Moreover, The contents are masterwork. you’ve done a excellent job on this topic!

  9. Another issue is that video gaming became one of the all-time greatest forms of fun for people spanning various ages. Kids participate in video games, and also adults do, too. The particular XBox 360 is just about the favorite gaming systems for people who love to have a huge variety of activities available to them, in addition to who like to learn live with people all over the world. Thank you for sharing your notions.

  10. As I website possessor I believe the content material here is rattling wonderful , appreciate it for your hard work. You should keep it up forever! Good Luck.

  11. Hey! Do you use Twitter? I’d like to follow you if that would be ok. I’m definitely enjoying your blog and look forward to new posts.

  12. What i do not understood is if truth be told how you are now not really a lot more smartly-preferred than you may be right now. You’re so intelligent. You realize thus significantly in terms of this topic, produced me in my view believe it from so many numerous angles. Its like men and women don’t seem to be fascinated until it is something to accomplish with Woman gaga! Your personal stuffs nice. All the time maintain it up!

  13. Yrefeqe表示:

    Привет!
    Приобрести диплом университета.
    heimur.ru/index.php?/topic/6329-купить-аттестат-9-класс-r178p

  14. Yrefqon表示:

    Привет, друзья!
    Приобрести диплом ВУЗа.
    lasergrafics.de/handel/artikel-b/#comment-110551

  15. Valuable information. Lucky me I found your website by accident, and I am shocked why this accident did not happened earlier! I bookmarked it.

  16. svqsecenu表示:

    Here, we take a look at what the previous nine Dutch managers in the English topflight accomplished – it does not all make for pretty reading! They have an incredible team, and a great manager named Jürgen Klopp, who’s this effervescent German guy. He has unlimited enthusiasm, gives very honest interviews, and has pioneered this style of soccer that he calls heavy-metal football, where it’s high pressing, high intensity, high energy. They have these two players in particular, Mohamed Salah—who was the best player in the Premier League a few seasons in a row—and Sadio Mane. A French club now have the longest active unbeaten record among Europe’s top five leagues. An interesting fact is that they have the youngest coach in any of the major professional leagues who began his managerial career on the Football Manager video game.
    https://bailoutdirectory.com/listings306263/nfl-scoreboard
    On the flip side, Liverpool rides high on momentum after securing two successive victories in the Premier League. They currently lead the table with 45 points from 20 matches. Liverpool, in their last Premier League appearance, thumped Newcastle United 4-2 at home. How to watch the Premier League match between Liverpool and Luton Town, as well as kick-off time and team news. You appear to be using an Android device. Please click here for instructions on how to subscribe to the feeds using Google Calendar syncing. The celebrated German manager announced his Liverpool departure earlier this season and has been bidding a long goodbye to the Reds since, and the final game was filled with emotion and tributes to Klopp. The celebrated German manager announced his Liverpool departure earlier this season and has been bidding a long goodbye to the Reds since, and the final game was filled with emotion and tributes to Klopp.

  17. Wow! This can be one particular of the most helpful blogs We’ve ever arrive across on this subject. Basically Great. I’m also an expert in this topic so I can understand your effort.

  18. I appreciate, lead to I discovered exactly what I used to be looking for. You have ended my 4 day lengthy hunt! God Bless you man. Have a great day. Bye

  19. vetzlgwqx表示:

    Clicking on any of these images will take you to an external site. The scoreline read 3-1 at the break and so it remained, with a scoreless second half. The scoreline read 3-1 at the break and so it remained, with a scoreless second half. Mon, 29 May, 2023 Abdoulaye Doucouré’s goal enough to extend top-flight stay; Leicester go down despite win over West Ham; Leeds lose to Spurs Images © Inpho Photography For the past four years, Andy Farrell has transformed the fear of heights that comes from being world No 1. Ireland have won 13 of their past 14 matches, which includes the not-inconsiderable feat of a Grand Slam and victories against every World Cup rival. Congratulations to Michelle O’Neill who has been appointed to the @UWCL Final refereeing team.The League of Ireland Official will be an Assistant Referee for the Final between FC Barcelona and VfL Wolfsburg in Eindhoven. #LOI pic.twitter lzL5avQLxR
    https://kameronzvpk062739.ka-blogs.com/82002212/serie-a-league-results
    Garth Crooks selected Newcastle striker Callum Wilson in his team of the week on the BBC website after he bagged another two goals on Saturday after despatching two penalties with Crooks saying: “The Newcastle striker was the coolest man in the stadium and has bounced back from a blip in goalscoring form to look as sharp as ever.” Chris Sutton has predicted that Everton will creep a point closer to Premier League safety with a 1-1 draw against Wolves at the Molineux Stadium on Saturday (20 May). Anyway, there is nothing that Tottenham fans can do now about Pochettino, who has already reportedly started planning for summer transfers with Chelsea. After the Premier League had to resume its 2019 20 season behind closed doors because of the coronavirus pandemic, the BBC broadcast live four PL matches from the campaign to enable more UK fans to enjoy the action from their homes.

  20. Great write-up, I am regular visitor of one?s website, maintain up the nice operate, and It is going to be a regular visitor for a lengthy time.

  21. Thanks for another fantastic article. Where else could anybody get that type of information in such an ideal way of writing? I’ve a presentation next week, and I am on the look for such information.

  22. Thanks for another informative blog. Where else could I get that kind of information written in such an ideal way? I have a project that I am just now working on, and I’ve been on the look out for such info.

  23. There is noticeably a bundle to know about this. I assume you made certain good factors in features also.

  24. Hello! This is my first visit to your blog! We are a team of volunteers and starting a new project in a community in the same niche. Your blog provided us valuable information to work on. You have done a extraordinary job!

  25. Please let me know if you’re looking for a article writer for your blog. You have some really good posts and I feel I would be a good asset. If you ever want to take some of the load off, I’d love to write some articles for your blog in exchange for a link back to mine. Please blast me an email if interested. Kudos!

  26. Greetings from Carolina! I’m bored to tears at work so I decided to check out your website on my iphone during lunch break. I love the information you present here and can’t wait to take a look when I get home. I’m amazed at how fast your blog loaded on my mobile .. I’m not even using WIFI, just 3G .. Anyhow, amazing site!

  27. Hi, Neat post. There’s a problem with your website in internet explorer, would test this? IE still is the market leader and a big portion of people will miss your excellent writing due to this problem.

  28. Thanks for these pointers. One thing I also believe is that often credit cards supplying a 0 interest often appeal to consumers along with zero rate of interest, instant acceptance and easy over-the-internet balance transfers, however beware of the main factor that is going to void your own 0 easy street annual percentage rate as well as throw one out into the terrible house in no time.

  29. hello there and thank you for your info ? I?ve definitely picked up anything new from right here. I did however expertise some technical points using this web site, since I experienced to reload the web site many times previous to I could get it to load correctly. I had been wondering if your web host is OK? Not that I am complaining, but sluggish loading instances times will often affect your placement in google and can damage your high-quality score if ads and marketing with Adwords. Anyway I?m adding this RSS to my email and could look out for much more of your respective exciting content. Ensure that you update this again very soon..

  30. Attractive section of content. I just stumbled upon your blog and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I will be subscribing to your augment and even I achievement you access consistently quickly.

發佈留言

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