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

  1. Please let me know if you’re looking for a article writer for your blog. You have some really good posts and I think I would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some material for your blog in exchange for a link back to mine. Please send me an email if interested. Cheers!

  2. KeithKef表示:

    pharmacie en ligne france livraison belgique Acheter Cialis 20 mg pas cher pharmacies en ligne certifiГ©es

  3. Allenacurf表示:

    pharmacie en ligne france pas cher: pharmacie en ligne – vente de mГ©dicament en ligne

  4. EdwardGROOM表示:

    Viagra sans ordonnance livraison 48h: viagra en ligne – Viagra femme ou trouver

  5. I would also like to add if you do not surely have an insurance policy or you do not take part in any group insurance, you may well make use of seeking the assistance of a health insurance agent. Self-employed or people with medical conditions ordinarily seek the help of one health insurance broker. Thanks for your text.

  6. What?s Taking place i am new to this, I stumbled upon this I have found It absolutely useful and it has aided me out loads. I’m hoping to give a contribution & help other users like its helped me. Good job.

  7. EdwardGROOM表示:

    pharmacie en ligne: Acheter Cialis – acheter mГ©dicament en ligne sans ordonnance

  8. Thanks for expressing your ideas. I might also like to say that video games have been at any time evolving. Technology advances and innovative developments have aided create sensible and enjoyable games. Most of these entertainment video games were not really sensible when the real concept was being experimented with. Just like other forms of technology, video games as well have had to progress as a result of many years. This itself is testimony on the fast progression of video games.

  9. Thanks for the article. I have usually observed that a lot of people are needing to lose weight since they wish to look slim along with attractive. Having said that, they do not constantly realize that there are additional benefits so that you can losing weight in addition. Doctors say that overweight people experience a variety of conditions that can be instantly attributed to their excess weight. The good news is that people who definitely are overweight plus suffering from diverse diseases are able to reduce the severity of the illnesses simply by losing weight. It is possible to see a slow but identifiable improvement with health if even a minor amount of weight loss is realized.

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

  11. Wow, superb blog layout! How lengthy have you been blogging for? you made blogging look easy. The whole look of your site is magnificent, as smartly as the content!

  12. My partner and I stumbled over here different web page and thought I might check things out. I like what I see so now i am following you. Look forward to checking out your web page yet again.

  13. Allenacurf表示:

    Viagra pas cher livraison rapide france: Meilleur Viagra sans ordonnance 24h – Viagra vente libre allemagne

  14. Does your blog have a contact page? I’m having a tough time locating it but, I’d like to send you an e-mail. I’ve got some suggestions for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it expand over time.

  15. EdwardGROOM表示:

    Viagra sans ordonnance 24h: Viagra pas cher paris – SildГ©nafil 100mg pharmacie en ligne

  16. RobertBlica表示:

    http://cenligne.com/# Pharmacie Internationale en ligne

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

  18. taurus zodiac表示:

    Hi there! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My blog looks weird when viewing from my iphone 4. I’m trying to find a theme or plugin that might be able to resolve this issue. If you have any recommendations, please share. Cheers!

  19. Thanks for this article. I’d personally also like to talk about the fact that it can possibly be hard while you are in school and just starting out to create a long credit rating. There are many college students who are simply trying to survive and have a good or favourable credit history can sometimes be a difficult point to have.

  20. Thanks for this article. I would also like to mention that it can end up being hard when you’re in school and starting out to establish a long credit rating. There are many college students who are only trying to endure and have a protracted or favourable credit history is often a difficult element to have.

  21. IgnacioSlima表示:

    trouver un mГ©dicament en pharmacie: pharmacie en ligne sans ordonnance – Pharmacie Internationale en ligne

  22. I?m not sure where you are getting your information, but good topic. I needs to spend some time learning much more or understanding more. Thanks for wonderful information I was looking for this information for my mission.

  23. What an eye-opening and meticulously-researched article! The author’s attention to detail and capability to present complex ideas in a understandable manner is truly praiseworthy. I’m thoroughly enthralled by the scope of knowledge showcased in this piece. Thank you, author, for providing your expertise with us. This article has been a true revelation!

  24. Jjizwc表示:

    loratadine child – claritin pills ernest loratadine medication specimen

  25. Thanks for these pointers. One thing I additionally believe is that often credit cards supplying a 0 rate of interest often bait consumers with zero monthly interest, instant approval and easy on the net balance transfers, nevertheless beware of the real factor that may void that 0 easy road annual percentage rate and as well as throw one out into the bad house fast.

  26. Allenacurf表示:

    Viagra homme prix en pharmacie: viagra en ligne – Prix du Viagra en pharmacie en France

  27. Hey! Someone in my Facebook group shared this site with us so I came to look it over. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Wonderful blog and superb design.

  28. EdwardGROOM表示:

    Pharmacie Internationale en ligne: kamagra gel – pharmacie en ligne

  29. Good post. I be taught something tougher on totally different blogs everyday. It should all the time be stimulating to read content from other writers and follow just a little one thing from their store. I?d desire to make use of some with the content material on my weblog whether or not you don?t mind. Natually I?ll give you a link in your web blog. Thanks for sharing.

  30. Allenacurf表示:

    Viagra vente libre allemagne: viagra sans ordonnance – SildГ©nafil 100mg pharmacie en ligne

發佈留言

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