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

  1. I loved up to you’ll obtain carried out proper here. The caricature is attractive, your authored subject matter stylish. however, you command get got an nervousness over that you want be handing over the following. in poor health certainly come further beforehand once more since exactly the similar just about a lot steadily within case you protect this hike.

  2. Can I just say what a relief to seek out somebody who actually is aware of what theyre talking about on the internet. You positively know find out how to bring a problem to gentle and make it important. Extra folks must read this and perceive this facet of the story. I cant imagine youre no more well-liked since you definitely have the gift.

  3. I like what you guys are up too. Such smart work and reporting! Keep up the superb works guys I have incorporated you guys to my blogroll. I think it will improve the value of my web site 🙂

  4. Whitescreen65表示:

    Thanks for expressing your ideas. I might also like to state that video games have been ever before evolving. Today’s technology and innovations have assisted create authentic and interactive games. These kinds of entertainment games were not really sensible when the actual concept was first being used. Just like other forms of technological know-how, video games way too have had to advance via many many years. This itself is testimony on the fast growth and development of video games.

  5. Отличный сайт! Всем рекомендую!справочник

  6. Thanks for this excellent article. One more thing to mention is that the majority of digital cameras can come equipped with the zoom lens that permits more or less of any scene to get included simply by ‘zooming’ in and out. These types of changes in {focus|focusing|concentration|target|the a**** length will be reflected within the viewfinder and on huge display screen right on the back of any camera.

  7. Whitescreen66表示:

    Thanks for your useful article. One other problem is that mesothelioma cancer is generally due to the breathing of materials from asbestos, which is a positivelly dangerous material. It truly is commonly found among staff in the construction industry who’ve long experience of asbestos. It’s also caused by living in asbestos insulated buildings for long periods of time, Genetics plays an important role, and some folks are more vulnerable on the risk when compared with others.

  8. Whitescreen67表示:

    Helpful info. Lucky me I discovered your website unintentionally, and I am stunned why this coincidence did not happened in advance! I bookmarked it.

  9. Thanks for enabling me to obtain new concepts about desktops. I also have the belief that certain of the best ways to help keep your notebook in excellent condition is to use a hard plastic case, or even shell, that fits over the top of the computer. These types of protective gear are usually model targeted since they are made to fit perfectly across the natural outer shell. You can buy all of them directly from owner, or through third party sources if they are available for your laptop, however only a few laptop can have a covering on the market. All over again, thanks for your suggestions.

  10. My brother suggested I would possibly like this website. He was totally right. This put up actually made my day. You cann’t consider just how much time I had spent for this info! Thank you!

  11. Thanks for your write-up. What I want to say is that when looking for a good on the internet electronics go shopping, look for a web page with complete information on key elements such as the security statement, security details, payment procedures, along with other terms and policies. Always take time to investigate the help plus FAQ segments to get a greater idea of how a shop is effective, what they can do for you, and the way you can make the most of the features.

  12. Whitescreen63表示:

    Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! However, how could we communicate?

  13. What?s Happening i’m new to this, I stumbled upon this I have found It absolutely useful and it has helped me out loads. I hope to give a contribution & aid different users like its helped me. Good job.

  14. Timothyzew表示:

    https://viagragenerico.site/# farmacia senza ricetta recensioni

  15. Timothyzew表示:

    http://kamagrait.pro/# farmacie online affidabili

  16. TomasRop表示:

    pillole per erezione in farmacia senza ricetta: viagra generico – viagra generico recensioni

  17. RandyLunda表示:

    comprare farmaci online con ricetta: Farmacie on line spedizione gratuita – farmacia online senza ricetta

  18. TomasRop表示:

    farmacie online sicure: Farmacie on line spedizione gratuita – Farmacia online piГ№ conveniente

  19. You really make it seem so easy with your presentation but I find this topic to be actually something that I think I would never understand. It seems too complicated and very broad for me. I’m looking forward for your next post, I?ll try to get the hang of it!

  20. RandyLunda表示:

    Farmacia online miglior prezzo: Cialis generico 5 mg prezzo – farmaci senza ricetta elenco

  21. I do enjoy the manner in which you have presented this specific situation and it does offer me personally some fodder for thought. Nonetheless, because of everything that I have seen, I simply trust when the opinions stack on that folks remain on issue and not embark upon a soap box associated with the news du jour. Anyway, thank you for this outstanding piece and though I do not concur with the idea in totality, I regard your point of view.

  22. Mazrkwx表示:

    Здравствуйте!
    Пошаговая инструкция по безопасной покупке диплома о высшем образовании
    rushkadiplomik.ru

  23. We are a group of volunteers and opening a brand new scheme in our community. Your website provided us with useful information to work on. You have performed a formidable job and our entire community can be thankful to you.

  24. I’m blown away by the quality of this content! The author has obviously put a tremendous amount of effort into exploring and structuring the information. It’s exciting to come across an article that not only provides useful information but also keeps the readers captivated from start to finish. Kudos to her for making such a masterpiece!

  25. Usually I don’t read article on blogs, but I wish to say that this write-up very forced me to try and do so! Your writing style has been amazed me. Thanks, quite nice post.

  26. Hi there just wanted to give you a brief heads up and let you know a few of the images aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same results.

  27. TomasRop表示:

    comprare farmaci online con ricetta: kamagra – Farmacia online miglior prezzo

  28. Timothyzew表示:

    https://kamagrait.pro/# Farmacie on line spedizione gratuita

  29. Hello, Neat post. There is a problem together with your web site in internet explorer, might check this? IE nonetheless is the market leader and a huge section of other people will pass over your great writing due to this problem.

發佈留言

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