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

  1. Whitescreen72表示:

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

  2. Whitescreen67表示:

    WONDERFUL Post.thanks for share..extra wait .. ?

  3. Good day! This is my first comment here so I just wanted to give a quick shout out and say I genuinely enjoy reading your articles. Can you suggest any other blogs/websites/forums that deal with the same topics? Many thanks!

  4. Great site! I recommend it to everyone!Private jet charter

  5. Whitescreen71表示:

    Thanks for your posting. I also feel that laptop computers have gotten more and more popular lately, and now tend to be the only sort of computer utilized in a household. It is because at the same time that they are becoming more and more cost-effective, their working power is growing to the point where these are as potent as personal computers coming from just a few in years past.

  6. Hi my family member! I want to say that this post is amazing, great written and include almost all important infos. I?d like to look more posts like this .

  7. One thing I have actually noticed is there are plenty of myths regarding the finance institutions intentions while talking about foreclosed. One fantasy in particular is the bank wants your house. The lending company wants your hard earned cash, not your own home. They want the cash they lent you having interest. Keeping away from the bank will still only draw the foreclosed summary. Thanks for your publication.

  8. What?s Going down i am new to this, I stumbled upon this I’ve discovered It absolutely helpful and it has helped me out loads. I hope to contribute & aid other customers like its helped me. Good job.

  9. Your place is valueble for me. Thanks!?

  10. Hi, i feel that i saw you visited my web site thus i came to ?return the want?.I’m attempting to to find issues to enhance my website!I assume its adequate to make use of some of your concepts!!

  11. Thank you for the good writeup. It in fact was a entertainment account it. Look advanced to far delivered agreeable from you! By the way, how could we keep up a correspondence?

  12. Hey there! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyhow, I’m definitely glad I found it and I’ll be book-marking and checking back frequently!

  13. Whitescreen68表示:

    What an eye-opening and well-researched article! The author’s meticulousness and ability to present intricate ideas in a comprehensible manner is truly commendable. I’m thoroughly captivated by the scope of knowledge showcased in this piece. Thank you, author, for offering your wisdom with us. This article has been a real game-changer!

  14. Thanks for the ideas shared in your blog. Another thing I would like to convey is that weight-loss is not information on going on a dietary fads and trying to get rid of as much weight that you can in a set period of time. The most effective way in losing weight is by getting it little by little and using some basic recommendations which can enable you to make the most through your attempt to lose fat. You may be aware and be following some tips, nevertheless reinforcing awareness never damages.

  15. Whitescreen72表示:

    This web site is known as a walk-by for all the info you needed about this and didn?t know who to ask. Glimpse here, and you?ll undoubtedly discover it.

  16. Lazrdxj表示:

    Привет!
    Мы предлагаем дипломы психологов, юристов, экономистов и прочих профессий по приятным ценам.
    diploms-rushkas.ru/kupit-diplom-bukhgaltera

  17. Would you be eager about exchanging links?

  18. I have seen a great deal of useful items on your site about computer systems. However, I have got the view that lap tops are still less than powerful sufficiently to be a wise decision if you often do tasks that require lots of power, including video touch-ups. But for world-wide-web surfing, word processing, and quite a few other prevalent computer work they are okay, provided you can’t mind the small screen size. Many thanks sharing your opinions.

  19. F*ckin? awesome things here. I?m very glad to see your post. Thanks a lot and i’m looking forward to contact you. Will you kindly drop me a e-mail?

  20. One thing I’d like to reply to is that weight loss program fast is possible by the appropriate diet and exercise. Ones size not simply affects appearance, but also the overall quality of life. Self-esteem, despression symptoms, health risks, along with physical skills are impacted in weight gain. It is possible to just make everything right but still gain. In such a circumstance, a condition may be the perpetrator. While too much food but not enough workout are usually at fault, common medical ailments and widespread prescriptions could greatly enhance size. Thanks a bunch for your post right here.

  21. Can I just say what a reduction to search out someone who truly is aware of what theyre speaking about on the internet. You definitely know methods to bring an issue to light and make it important. Extra folks have to learn this and understand this facet of the story. I cant believe youre not more widespread since you undoubtedly have the gift.

  22. Trefmvy表示:

    Здравствуйте!
    Быстрое обучение и получение диплома магистра – возможно ли это?
    mans-diplomy.ru/kupit-diplom-ekaterinburg
    Рады оказать помощь!.

  23. Whitescreen72表示:

    Once I originally commented I clicked the -Notify me when new feedback are added- checkbox and now each time a comment is added I get four emails with the identical comment. Is there any way you may take away me from that service? Thanks!

  24. Thanks a lot for your post. I would like to comment that the price of car insurance varies from one insurance plan to another, mainly because there are so many different issues which bring about the overall cost. For instance, the make and model of the auto will have an enormous bearing on the price. A reliable old family car will have an inexpensive premium than a flashy racecar.

  25. Georgedrync表示:

    natural viagra: Viagra without a doctor prescription – order viagra online

  26. Hello there! This is my 1st comment here so I just wanted to give a quick shout out and say I genuinely enjoy reading through your blog posts. Can you suggest any other blogs/websites/forums that cover the same subjects? Many thanks!

  27. Georgedrync表示:

    where to buy generic cialis?: Generic Cialis without a doctor prescription – canada cialis trial

  28. Georgedrync表示:

    buy cialis shipment to russia: Buy Cialis online – canadian pharmacy viagra cialis

  29. Whitescreen66表示:

    I have noticed that car insurance companies know the cars which are liable to accidents as well as other risks. Additionally, these people know what kind of cars are susceptible to higher risk plus the higher risk they have got the higher your premium fee. Understanding the straightforward basics connected with car insurance can help you choose the right type of insurance policy that can take care of your needs in case you happen to be involved in any accident. Thank you sharing the particular ideas on your blog.

發佈留言

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