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

  1. I am really enjoying the theme/design of your weblog. Do you ever run into any web browser compatibility issues? A few of my blog visitors have complained about my website not working correctly in Explorer but looks great in Opera. Do you have any solutions to help fix this issue?

  2. Hello, i read your blog from time to time and i own a similar one and i was just wondering if you get a lot of spam feedback? If so how do you protect against it, any plugin or anything you can advise? I get so much lately it’s driving me mad so any help is very much appreciated.

  3. I like the valuable info you provide in your articles. I will bookmark your weblog and check again here frequently. I’m quite certain I will learn lots of new stuff right here! Good luck for the next!

  4. Hi, I think your website might be having browser compatibility issues. When I look at your blog site 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, wonderful blog!

  5. It is best to participate in a contest for among the best blogs on the web. I’ll suggest this web site!

  6. Oh my goodness! an amazing article dude. Thanks Nonetheless I am experiencing challenge with ur rss . Don?t know why Unable to subscribe to it. Is there anybody getting equivalent rss problem? Anybody who knows kindly respond. Thnkx

  7. I believe that avoiding highly processed foods could be the first step for you to lose weight. They may taste excellent, but processed foods include very little vitamins and minerals, making you eat more in order to have enough power to get over the day. If you’re constantly feeding on these foods, switching to whole grains and other complex carbohydrates will assist you to have more vigor while ingesting less. Interesting blog post.

  8. I like the helpful info you provide in your articles. I?ll bookmark your blog and check again here regularly. I am quite sure I?ll learn a lot of new stuff right here! Best of luck for the next!

  9. great publish, very informative. I’m wondering why the opposite experts of this sector do not notice this. You must proceed your writing. I am sure, you’ve a great readers’ base already!

  10. Generally I do not read article on blogs, however I would like to say that this write-up very forced me to take a look at and do it! Your writing taste has been surprised me. Thank you, very great article.

  11. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your weblog? My blog site is in the exact same area of interest as yours and my users would definitely benefit from a lot of the information you provide here. Please let me know if this okay with you. Thank you!

  12. I also believe that mesothelioma cancer is a extraordinary form of cancer that is normally found in those people previously subjected to asbestos. Cancerous tissues form within the mesothelium, which is a protecting lining that covers most of the body’s areas. These cells normally form while in the lining in the lungs, abdomen, or the sac that really encircles the heart. Thanks for expressing your ideas.

  13. Thanks a lot for the helpful article. It is also my belief that mesothelioma cancer has an extremely long latency time, which means that warning signs of the disease won’t emerge until finally 30 to 50 years after the primary exposure to mesothelioma. Pleural mesothelioma, that is the most common style and has effects on the area across the lungs, might cause shortness of breath, breasts pains, including a persistent coughing, which may cause coughing up bloodstream.

  14. Good blog! I truly love how it is easy on my eyes and the data are well written. I’m wondering how I might be notified whenever a new post has been made. I have subscribed to your RSS feed which must do the trick! Have a nice day!

  15. Greetings from Florida! I’m bored at work so I decided to browse your site on my iphone during lunch break. I enjoy the knowledge you provide here and can’t wait to take a look when I get home. I’m surprised at how quick your blog loaded on my phone .. I’m not even using WIFI, just 3G .. Anyways, excellent blog!

  16. Audio began playing as soon as I opened up this web-site, so irritating!

  17. you are really a good webmaster. The website loading speed is amazing. It seems that you are doing any unique trick. Also, The contents are masterwork. you’ve done a fantastic job on this topic!

  18. Greetings from Carolina! I’m bored to tears at work so I decided to check out your site on my iphone during lunch break. I really like the info 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 phone .. I’m not even using WIFI, just 3G .. Anyways, superb site!

  19. Awesome blog! Do you have any suggestions for aspiring writers? I’m planning to start my own site soon but I’m a little lost on everything. Would you advise starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely confused .. Any suggestions? Thank you!

  20. I savour, cause I discovered just what I was taking a look for. You have ended my 4 day long hunt! God Bless you man. Have a nice day. Bye

  21. biardiova表示:

    buy priligy in the us A representative experiment is shown n 4

  22. Today, while I was at work, my cousin stole my apple ipad and tested to see if it can survive a thirty foot drop, just so she can be a youtube sensation. My apple ipad is now destroyed and she has 83 views. I know this is entirely off topic but I had to share it with someone!

  23. Youre so cool! I dont suppose Ive learn anything like this before. So nice to seek out someone with some original thoughts on this subject. realy thank you for starting this up. this web site is one thing that’s wanted on the internet, someone with slightly originality. useful job for bringing something new to the internet!

  24. Right now it appears like Expression Engine is the best blogging platform available right now. (from what I’ve read) Is that what you’re using on your blog?

  25. whoah this blog is wonderful i like studying your articles. Stay up the great paintings! You recognize, many individuals are looking round for this information, you can help them greatly.

  26. Hi there! This is kind of off topic but I need some advice from an established blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about creating my own but I’m not sure where to start. Do you have any points or suggestions? Appreciate it

  27. This comes in handy when a pit reporter and cameraman need to solicit some real-time thoughts from a stressed-out crew chief in the middle of a tight race.

  28. whoah this blog is fantastic i like studying your articles. Keep up the good paintings! You know, many persons are hunting around for this information, you can help them greatly.

  29. It is indeed my belief that mesothelioma can be the most fatal cancer. It contains unusual qualities. The more I look at it the greater I am confident it does not conduct itself like a real solid cells cancer. If mesothelioma is often a rogue viral infection, then there is the chance for developing a vaccine along with offering vaccination to asbestos subjected people who are open to high risk regarding developing foreseeable future asbestos linked malignancies. Thanks for discussing your ideas for this important ailment.

發佈留言

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