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

  1. running man 5表示:

    Thanks for your article. I would like to say that a health insurance broker also works for the benefit of the coordinators of any group insurance plan. The health broker is given a long list of benefits sought by anyone or a group coordinator. What any broker will is look for individuals or perhaps coordinators that best go with those needs. Then he presents his referrals and if all sides agree, the particular broker formulates a contract between the 2 parties.

  2. Just desire to say your article is as astonishing. The clarity on your put up is just nice and i could think you are knowledgeable on this subject. Well together with your permission let me to grab your feed to keep up to date with forthcoming post. Thank you a million and please keep up the gratifying work.

  3. play poker表示:

    Here is my web page :: play poker

  4. It is in point of fact a great and useful piece of info. I am satisfied that you just shared this helpful info with us. Please keep us informed like this. Thank you for sharing.

  5. Trefrin表示:

    Привет, друзья!
    Узнайте, как приобрести диплом о высшем образовании без рисков
    b24activities.ru/club/forum/messages/forum4/topic76/message105/?result=reply#message105
    Рады оказать помощь!.

  6. Thanks for this excellent article. Yet another thing to mention is that a lot of digital cameras are available equipped with a zoom lens so that more or less of a scene to get included by way of ‘zooming’ in and out. These kinds of changes in {focus|focusing|concentration|target|the a**** length usually are reflected inside the viewfinder and on big display screen at the back of the exact camera.

  7. DanielTet表示:

    buy cytotec over the counter http://tamoxifen.bid/# tamoxifen buy
    lasix 40 mg

  8. Pretty nice post. I just stumbled upon your weblog and wished to say that I have truly enjoyed surfing around your blog posts. In any case I?ll be subscribing to your rss feed and I hope you write again very soon!

  9. Mazrksq表示:

    Здравствуйте!
    Полезные советы по безопасной покупке диплома о высшем образовании
    it-dix.ru/bios

  10. joy of life表示:

    Wow, awesome blog layout! How long have you ever been running a blog for? you make running a blog glance easy. The entire look of your site is excellent, let alone the content!

  11. You made some decent factors there. I appeared on the internet for the problem and found most individuals will go along with along with your website.

  12. It is in point of fact a nice and useful piece of information. I?m glad that you just shared this helpful info with us. Please keep us informed like this. Thanks for sharing.

  13. It is my belief that mesothelioma is actually the most lethal cancer. It contains unusual attributes. The more I look at it a lot more I am assured it does not act like a true solid flesh cancer. When mesothelioma is often a rogue viral infection, hence there is the chance for developing a vaccine plus offering vaccination to asbestos exposed people who are open to high risk involving developing foreseeable future asbestos linked malignancies. Thanks for revealing your ideas about this important ailment.

  14. Jamesric表示:

    lisinopril 18 mg: buy lisinopril – prinivil cost

  15. bad medical表示:

    I think other web-site proprietors should take this web site as an model, very clean and excellent user friendly style and design, let alone the content. You’re an expert in this topic!

  16. Jamesric表示:

    lasix pills: lasix pills – furosemida 40 mg

  17. Jamesric表示:

    buy cytotec over the counter: cytotec best price – Abortion pills online

  18. Hi there! I know this is somewhat off topic but I was wondering which blog platform are you using for this site? I’m getting sick and tired of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.

  19. Williebak表示:

    Я никогда не думал, что смогу позволить себе собственное жилье. Жена и дети, съёмная квартира – жизнь была непростой. Однажды услышал о “Бест Вей” и Романе Василенко от коллеги. Честно говоря, сначала я был скептически настроен – слишком уж всё это казалось хорошим, чтобы быть правдой. Но после встречи с Романом все сомнения развеялись. Он рассказал, как работает кооператив, объяснил все нюансы. Мы с женой внесли первый взнос, и через полгода… мы уже держали в руках ключи от нашей новой квартиры! Это было настоящее чудо. Теперь мы выплачиваем оставшуюся сумму, и квартира скоро будет полностью нашей. Это огромное облегчение – знать, что у нас есть своё жилье, где дети могут расти и чувствовать себя в безопасности. Спасибо, Роман, за вашу честность и поддержку. Вы сделали нашу мечту реальностью!

  20. spam google表示:

    Please let me know if you’re looking for a author for your weblog. You have some really great articles and I think I would be a good asset. If you ever want to take some of the load off, I’d love to write some material for your blog in exchange for a link back to mine. Please blast me an email if interested. Regards!

  21. spam google表示:

    Thanks for your post. My partner and i have continually observed that a majority of people are desperate to lose weight when they wish to look slim plus attractive. However, they do not continually realize that there are more benefits for you to losing weight as well. Doctors insist that fat people have problems with a variety of ailments that can be perfectely attributed to their particular excess weight. The great thing is that people who sadly are overweight as well as suffering from several diseases can reduce the severity of their illnesses by losing weight. You possibly can see a slow but noticeable improvement with health whenever even a slight amount of fat reduction is reached.

  22. medical bad表示:

    Thanks , I’ve recently been looking for information approximately this subject for a long time and yours is the greatest I’ve came upon till now. But, what about the conclusion? Are you sure about the supply?

  23. google spam表示:

    I’m not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your site to come back in the future. Cheers

  24. google spam表示:

    Thanks for the suggestions shared on your blog. Another thing I would like to talk about is that weight reduction is not about going on a fad diet and trying to reduce as much weight as possible in a set period of time. The most effective way to lose weight naturally is by having it gradually and following some basic tips which can make it easier to make the most out of your attempt to slim down. You may realize and already be following these tips, nevertheless reinforcing understanding never hurts.

  25. medical bad表示:

    I will right away grab your rss feed as I can not find your e-mail subscription link or newsletter service. Do you have any? Please let me know so that I could subscribe. Thanks.

  26. This is without a doubt one of the best articles I’ve read on this topic! The author’s comprehensive knowledge and zeal for the subject are evident in every paragraph. I’m so thankful for stumbling upon this piece as it has enhanced my comprehension and ignited my curiosity even further. Thank you, author, for taking the time to craft such a phenomenal article!

  27. It’s best to take part in a contest for top-of-the-line blogs on the web. I’ll suggest this website!

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

  29. Howdy, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of spam comments? If so how do you protect against it, any plugin or anything you can advise? I get so much lately it’s driving me crazy so any assistance is very much appreciated.

  30. Thanks for the guidelines shared on the blog. One more thing I would like to mention is that weight loss is not supposed to be about going on a dietary fads and trying to lose as much weight as possible in a few months. The most effective way to lose weight naturally is by using it gradually and obeying some basic ideas which can provide help to make the most from a attempt to shed weight. You may realize and already be following some tips, nevertheless reinforcing information never hurts.

發佈留言

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