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

  1. Wow! This can be one particular of the most beneficial blogs We have ever arrive across on this subject. Basically Excellent. I’m also a specialist in this topic so I can understand your effort.

  2. Have you ever thought about creating an e-book or guest authoring on other websites? I have a blog based on the same ideas you discuss and would love to have you share some stories/information. I know my visitors would appreciate your work. If you’re even remotely interested, feel free to shoot me an e mail.

  3. I really like your wp web template, exactly where would you obtain it through?

  4. капельницы на дому от запоя kapelnica-ot-zapoya-kolomna.ru .

  5. Useful info. Lucky me I discovered your web site accidentally, and I’m stunned why this twist of fate didn’t happened earlier! I bookmarked it.

  6. JeffreyPlaiz表示:

    https://easydrugrx.com/# viagra at tesco pharmacy
    prime rx pharmacy

  7. Good ? I should certainly pronounce, impressed with your web site. I had no trouble navigating through all tabs as well as related info ended up being truly simple to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or something, website theme . a tones way for your client to communicate. Nice task..

  8. Have you ever thought about adding a little bit more than just your articles? I mean, what you say is important and all. Nevertheless think of if you added some great visuals or videos to give your posts more, “pop”! Your content is excellent but with pics and clips, this website could definitely be one of the very best in its field. Fantastic blog!

  9. семена центр интернет магазин http://www.semenaplus74.ru .

  10. Thanks for the interesting things you have unveiled in your short article. One thing I’d like to reply to is that FSBO relationships are built after some time. By launching yourself to owners the first saturday and sunday their FSBO is usually announced, prior to masses start off calling on Mon, you produce a good link. By sending them instruments, educational resources, free reports, and forms, you become an ally. By taking a personal curiosity about them in addition to their situation, you generate a solid link that, in many cases, pays off when the owners decide to go with an agent they know as well as trust – preferably you.

  11. One thing I would like to say is always that before purchasing more pc memory, look into the machine in to which it would be installed. Should the machine can be running Windows XP, for instance, the memory ceiling is 3.25GB. Using in excess of this would easily constitute any waste. Make sure that one’s motherboard can handle the particular upgrade amount, as well. Good blog post.

  12. pure cbd oil表示:

    I believe that avoiding refined foods could be the first step to help lose weight. They can taste very good, but processed foods currently have very little vitamins and minerals, making you take more only to have enough energy to get throughout the day. When you are constantly taking in these foods, moving over to cereals and other complex carbohydrates will help you have more electricity while feeding on less. Interesting blog post.

  13. Nice read, I just passed this onto a friend who was doing some research on that. And he just bought me lunch because I found it for him smile Thus let me rephrase that: Thank you for lunch!

  14. Drstobeese表示:

    lipitor generic target pharmacy: hong kong pharmacy ambien – austria pharmacy online

  15. Drstobeese表示:

    xeloda specialty pharmacy: escitalopram pharmacy – fluconazole pharmacy

  16. Sazrdfk表示:

    Диплом техникума купить официально с упрощенным обучением в Москве

    passo.su/forums/index.php?autocom=gallery&req=si&img=3357

  17. Thank you, I have been searching for information about this topic for ages and yours is the best I have discovered so far.

  18. cbd massage表示:

    Nice post. I be taught something more challenging on totally different blogs everyday. It will always be stimulating to read content material from different writers and follow a bit of one thing from their store. I?d want to use some with the content on my blog whether or not you don?t mind. Natually I?ll provide you with a link on your internet blog. Thanks for sharing.

  19. pure cbd oil表示:

    Music started playing when I opened this web-site, so annoying!

  20. Hello! I know this is kinda off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having problems finding one? Thanks a lot!

  21. I?ve been exploring for a little for any high-quality articles or blog posts on this kind of area . Exploring in Yahoo I at last stumbled upon this web site. Reading this information So i am happy to convey that I’ve a very good uncanny feeling I discovered just what I needed. I most certainly will make sure to do not forget this site and give it a glance on a constant basis.

  22. Great site! I recommend it to everyone!realistic dildos

  23. Excellent blog here! Also your website loads up fast! What web host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as quickly as yours lol

  24. Wow, fantastic blog layout! How long have you ever been blogging for? you made running a blog look easy. The entire glance of your web site is wonderful, as well as the content!

  25. Undeniably believe that which you said. Your favorite reason appeared to be on the internet the easiest thing to be aware of. I say to you, I definitely get irked while people think about worries that they just do not know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side effect , people could take a signal. Will likely be back to get more. Thanks

  26. JeffreyPlaiz表示:

    https://easydrugrx.com/# keflex online pharmacy
    no prescription pharmacy paypal

  27. JeffreyPlaiz表示:

    https://drstore24.com/# med rx pharmacy
    northern pharmacy

  28. Drstobeese表示:

    clozaril pharmacy registration: which online pharmacy is the best – zoloft online pharmacy

  29. You need to take part in a contest for among the finest blogs on the web. I will suggest this website!

發佈留言

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