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

  1. With havin so much content do you ever run into any problems of plagorism or copyright violation? My blog has a lot of unique content I’ve either authored myself or outsourced but it seems a lot of it is popping it up all over the internet without my agreement. Do you know any methods to help reduce content from being ripped off? I’d truly appreciate it.

  2. After research a few of the weblog posts on your web site now, and I truly like your means of blogging. I bookmarked it to my bookmark web site listing and can be checking back soon. Pls check out my web page as properly and let me know what you think.

  3. I was more than happy to search out this internet-site.I wanted to thanks on your time for this wonderful learn!! I undoubtedly having fun with every little little bit of it and I have you bookmarked to take a look at new stuff you blog post.

  4. cbd massage表示:

    Today, I went to the beach with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!

  5. Thca Flower表示:

    Thanks for every other informative web site. Where else could I get that type of information written in such an ideal method? I have a undertaking that I am simply now working on, and I have been at the look out for such information.

  6. Thca Flower表示:

    whoah this weblog is fantastic i like studying your articles. Keep up the good paintings! You realize, lots of individuals are searching round for this info, you could help them greatly.

  7. SEO_pdMa表示:

    продвижение и раскрутка сайтов в москве https://prodvizhenie-sajtov-v-moskve115.ru/ .

  8. Thca Flower表示:

    My partner and I stumbled over here coming from a different page and thought I might check things out. I like what I see so i am just following you. Look forward to looking at your web page for a second time.

  9. Josephton表示:

    The world’s most liveable cities for 2024
    смотреть гей порно

    It’s considered among the most beautiful cities in the world to visit, and it seems that Vienna may also be an unbeatable place to live.

    The Austrian city has been crowned the most liveable city in the world yet again in the annual list from the Economist Intelligence Unit (EIU), which was released today.

    The EIU, a sister organization to The Economist, ranked 173 cities across the globe on a number of significant factors, including health care, culture and environment, stability, infrastructure and education.

    Vienna topped the list for the third consecutive year, receiving “perfect” scores in four out of five of the categories — the city was marked lower for culture and environment due to an apparent lack of significant sporting events.
    Just behind the Austrian capital, Denmark’s Copenhagen retained its second place position, while Switzerland’s Zurich moved up from sixth place to third on the list.

    Australia’s Melbourne fell from third to fourth place, while Canadian city Calgary tied for fifth place with Swiss city Geneva.

    Canada’s Vancouver and Australia’s Sydney were in joint seventh place, and Japan’s Osaka and New Zealand’s Auckland rounded out the top 10 in joint ninth place.

  10. Thca Flower表示:

    Thanks a bunch for sharing this with all people you really understand what you are talking about! Bookmarked. Please additionally seek advice from my site =). We will have a hyperlink exchange contract between us!

  11. Thanks for expressing your ideas. Another thing is that college students have a choice between fed student loan plus a private education loan where it truly is easier to go for student loan consolidation than with the federal student loan.

  12. Thca Flower表示:

    I just added this webpage to my google reader, excellent stuff. Cannot get enough!

  13. Valuable information. Lucky me I found your site by accident, and I’m shocked why this accident didn’t happened earlier! I bookmarked it.

  14. cbd massage表示:

    Today, taking into consideration the fast life-style that everyone leads, credit cards get this amazing demand throughout the market. Persons throughout every arena are using the credit card and people who not using the credit cards have prepared to apply for one. Thanks for revealing your ideas on credit cards.

  15. Thca Flower表示:

    When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three e-mails with the same comment. Is there any way you can remove me from that service? Thanks!

  16. you’re really a good webmaster. The website loading speed is incredible. It seems that you are doing any unique trick. Moreover, The contents are masterwork. you have done a fantastic job on this topic!

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

  18. Thca Flower表示:

    I’m so happy to read this. This is the kind of manual that needs to be given and not the accidental misinformation that’s at the other blogs. Appreciate your sharing this greatest doc.

  19. Thca Flower表示:

    excellent post, very informative. I wonder why the other specialists of this sector do not notice this. You should continue your writing. I’m sure, you’ve a huge readers’ base already!

  20. cbd massage表示:

    I am very happy to read this. This is the kind of manual that needs to be given and not the accidental misinformation that’s at the other blogs. Appreciate your sharing this greatest doc.

  21. Thca Flower表示:

    Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why throw away your intelligence on just posting videos to your site when you could be giving us something informative to read?

  22. In line with my research, after a property foreclosure home is sold at a sale, it is common to the borrower to still have the remaining balance on the loan. There are many loan merchants who seek to have all charges and liens paid off by the up coming buyer. Nevertheless, depending on certain programs, restrictions, and state legal guidelines there may be some loans that aren’t easily resolved through the shift of financial products. Therefore, the responsibility still falls on the client that has obtained his or her property in foreclosure. Thanks for sharing your opinions on this site.

  23. I found your weblog website on google and verify a few of your early posts. Proceed to maintain up the excellent operate. I simply further up your RSS feed to my MSN Information Reader. In search of forward to reading more from you in a while!?

  24. Good site! I really love how it is simple on my eyes and the data are well written. I am wondering how I could be notified when a new post has been made. I’ve subscribed to your feed which must do the trick! Have a nice day!

  25. Hi there, just changed into aware of your blog thru Google, and found that it’s truly informative. I am going to be careful for brussels. I will be grateful when you proceed this in future. Many other folks shall be benefited out of your writing. Cheers!

  26. Great work! This is the type of information that should be shared around the internet. Shame on Google for not positioning this post higher! Come on over and visit my website . Thanks =)

  27. Thca Flower表示:

    Furthermore, i believe that mesothelioma cancer is a extraordinary form of melanoma that is generally found in people previously subjected to asbestos. Cancerous cells form inside mesothelium, which is a protective lining which covers a lot of the body’s internal organs. These cells usually form in the lining of the lungs, mid-section, or the sac that encircles one’s heart. Thanks for sharing your ideas.

  28. En guvenilir kumarhaneyi tavsiye ederim Sweet bonanza

  29. Thca Flower表示:

    Attractive part of content. I simply stumbled upon your weblog and in accession capital to claim that I get in fact loved account your blog posts. Anyway I will be subscribing on your feeds and even I achievement you get admission to persistently fast.

  30. Hayallerinizdeki kumarhane Sweet bonanza

發佈留言

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