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

  1. Hiya, I’m really glad I have found this information. Today bloggers publish just about gossips and web and this is really frustrating. A good site with interesting content, that’s what I need. Thank you for keeping this website, I will be visiting it. Do you do newsletters? Cant find it.

  2. Can I simply say what a relief to find someone who really is aware of what theyre talking about on the internet. You undoubtedly know the best way to convey an issue to mild and make it important. More folks have to learn this and understand this aspect of the story. I cant believe youre not more popular because you positively have the gift.

  3. Hey There. I discovered your weblog the use of msn. This is an extremely neatly written article. I?ll make sure to bookmark it and come back to learn more of your helpful information. Thank you for the post. I will certainly return.

  4. I think one of your ads triggered my internet browser to resize, you may well want to put that on your blacklist.

  5. Thank you sharing these kind of wonderful content. In addition, an excellent travel along with medical insurance strategy can often eradicate those considerations that come with visiting abroad. Your medical emergency can in the near future become expensive and that’s bound to quickly place a financial load on the family finances. Having in place the excellent travel insurance offer prior to setting off is well worth the time and effort. Thanks

  6. Hello there, I found your web site via Google while looking for a related topic, your web site came up, it looks good. I have bookmarked it in my google bookmarks.

  7. It?s hard to find knowledgeable individuals on this subject, however you sound like you recognize what you?re speaking about! Thanks

  8. I learned more interesting things on this weight loss issue. One issue is a good nutrition is vital if dieting. A massive reduction in junk food, sugary ingredients, fried foods, sweet foods, beef, and whitened flour products could possibly be necessary. Keeping wastes unwanted organisms, and poisons may prevent objectives for fat loss. While a number of drugs for the short term solve the matter, the terrible side effects will not be worth it, and so they never supply more than a non permanent solution. It is just a known indisputable fact that 95 of dietary fads fail. Thank you for sharing your ideas on this blog.

  9. Thanks for revealing your ideas. I’d personally also like to mention that video games have been ever evolving. Technology advances and revolutions have made it simpler to create practical and interactive games. These kind of entertainment games were not that sensible when the real concept was first of all being experimented with. Just like other designs of technology, video games also have had to develop through many many years. This is testimony for the fast development of video games.

  10. I believe that avoiding highly processed foods is the first step to lose weight. They might taste beneficial, but refined foods have very little vitamins and minerals, making you take more to have enough energy to get with the day. Should you be constantly taking in these foods, switching to whole grains and other complex carbohydrates will help you have more vigor while ingesting less. Great blog post.

  11. I was wondering if you ever considered 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 images. Maybe you could space it out better?

  12. Attractive element of content. I simply stumbled upon your site and in accession capital to say that I get in fact loved account your blog posts. Any way I?ll be subscribing for your feeds or even I achievement you get entry to constantly quickly.

  13. It?s really a great and useful piece of info. I?m glad that you shared this helpful information with us. Please keep us informed like this. Thanks for sharing.

  14. Thanks for the helpful write-up. It is also my opinion that mesothelioma has an really long latency period, which means that signs and symptoms of the disease may well not emerge until eventually 30 to 50 years after the preliminary exposure to mesothelioma. Pleural mesothelioma, which can be the most common form and has an effect on the area round the lungs, will cause shortness of breath, chest pains, and also a persistent cough, which may bring on coughing up our blood.

  15. Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a little bit, but instead of that, this is excellent blog. An excellent read. I will definitely be back.

  16. Hi there, just was aware of your blog through Google, and located that it’s truly informative. I am going to be careful for brussels. I?ll appreciate if you happen to continue this in future. A lot of other people will be benefited from your writing. Cheers!

  17. It’s a pity you don’t have a donate button! I’d definitely donate to this superb blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this website with my Facebook group. Talk soon!

  18. I am no longer certain where you are getting your information, but great topic. I must spend some time studying much more or figuring out more. Thanks for magnificent information I was in search of this info for my mission.

  19. Merchant bankers are a group of professionals who provide capital to companies in the form of share ownership instead of loans.

  20. Another important aspect is that if you are a senior citizen, travel insurance with regard to pensioners is something you ought to really look at. The mature you are, the more at risk you will be for allowing something bad happen to you while in another country. If you are never covered by many comprehensive insurance policies, you could have a number of serious troubles. Thanks for giving your guidelines on this website.

  21. Today, taking into consideration the fast life-style that everyone is having, credit cards get this amazing demand throughout the economy. Persons from every arena are using the credit card and people who not using the credit card have made arrangements to apply for just one. Thanks for expressing your ideas on credit cards.

  22. I have realized some significant things through your site post. One other point I would like to convey is that there are plenty of games in the marketplace designed specially for preschool age youngsters. They involve pattern identification, colors, family pets, and styles. These often focus on familiarization as an alternative to memorization. This helps to keep little children engaged without feeling like they are learning. Thanks

  23. For this reason, one must take on good option to avoid wasting their invaluable money as well as try to reduce them from any great loss.

  24. you’re truly a excellent webmaster. The web site loading velocity is incredible. It seems that you are doing any distinctive trick. In addition, The contents are masterwork. you have done a fantastic job on this topic!

  25. Whats up very nice site!! Man .. Excellent .. Superb .. I will bookmark your blog and take the feeds additionally?I’m glad to seek out so many helpful information right here in the submit, we’d like develop extra strategies in this regard, thanks for sharing. . . . . .

  26. Stanleyinolf表示:

    buy furosemide online lasix furosemide 40 mg furosemide 100mg

  27. flying high表示:

    Hey! I just wanted to ask if you ever have any issues with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no backup. Do you have any solutions to prevent hackers?

  28. hello!,I like your writing very much! share we communicate more about your article on AOL? I need a specialist on this area to solve my problem. Maybe that’s you! Looking forward to see you.

  29. li表示:

    My brother recommended I might like this website. He was entirely right. This post truly made my day. You can not imagine simply how much time I had spent for this info! Thanks!

  30. Jamesric表示:

    lasix furosemide 40 mg: buy furosemide – furosemide 40 mg

發佈留言

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