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

  1. Wow that was odd. I just wrote an really long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say wonderful blog!

  2. One thing I’d prefer to touch upon is that fat burning plan fast can be carried out by the perfect diet and exercise. An individual’s size not just affects the look, but also the actual quality of life. Self-esteem, despression symptoms, health risks, along with physical abilities are afflicted in fat gain. It is possible to just make everything right but still gain. Should this happen, a medical problem may be the perpetrator. While a lot of food but not enough body exercise are usually the culprit, common medical ailments and widespread prescriptions can easily greatly increase size. Thanks alot : ) for your post in this article.

  3. Hi my friend! I want to say that this article is awesome, nice written and include approximately all vital infos. I would like to see more posts like this.

  4. Just desire to say your article is as astounding. The clearness to your submit is simply nice and that i could suppose you’re a professional on this subject. Well along with your permission let me to seize your feed to keep up to date with impending post. Thank you a million and please keep up the enjoyable work.

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

  6. Thanks for this excellent article. One other thing is that many digital cameras can come equipped with some sort of zoom lens that allows more or less of the scene to generally be included by way of ‘zooming’ in and out. These kinds of changes in {focus|focusing|concentration|target|the a**** length are usually reflected in the viewfinder and on massive display screen right at the back of your camera.

  7. Thanks for the article. My partner and i have generally observed that most people are desirous to lose weight because they wish to appear slim as well as attractive. Nonetheless, they do not continually realize that there are additional benefits just for losing weight also. Doctors say that overweight people suffer from a variety of health conditions that can be perfectely attributed to the excess weight. The great thing is that people who are overweight and also suffering from several diseases are able to reduce the severity of their particular illnesses by losing weight. You are able to see a gradual but marked improvement in health whenever even a small amount of weight loss is reached.

  8. Thanks for your post. One other thing is when you are promoting your property by yourself, one of the concerns you need to be alert to upfront is when to deal with house inspection reports. As a FSBO owner, the key to successfully transferring your property as well as saving money about real estate agent revenue is expertise. The more you know, the softer your property sales effort will likely be. One area exactly where this is particularly critical is assessments.

  9. Wonderful blog! I found it while browsing on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Thanks

  10. Good post. I learn something more difficult on totally different blogs everyday. It is going to at all times be stimulating to learn content material from different writers and follow a little something from their store. I?d prefer to make use of some with the content on my weblog whether you don?t mind. Natually I?ll offer you a hyperlink in your internet blog. Thanks for sharing.

  11. I truly appreciate this post. I?ve been looking everywhere for this! Thank goodness I found it on Bing. You’ve made my day! Thanks again

  12. Thanks for giving your ideas with this blog. Furthermore, a fairy tale regarding the banking institutions intentions if talking about home foreclosure is that the standard bank will not take my repayments. There is a fair bit of time the bank is going to take payments occasionally. If you are also deep in the hole, they are going to commonly desire that you pay the actual payment fully. However, that doesn’t mean that they will have any sort of payments at all. In the event you and the traditional bank can manage to work anything out, a foreclosure process may halt. However, should you continue to pass up payments in the new plan, the foreclosure process can just pick up from where it left off.

  13. Some tips i have observed in terms of pc memory is that there are specific features such as SDRAM, DDR and so on, that must match the requirements of the mother board. If the pc’s motherboard is kind of current while there are no main system issues, replacing the memory literally takes under a couple of hours. It’s one of several easiest pc upgrade methods one can picture. Thanks for expressing your ideas.

  14. Robertontof表示:

    Юридический портал Соцправ.ру
    264 гпк
    – окажет вам помощь в решении сложных правовых проблем. У нас вы найдете качественную и грамотную юридическую поддержку в любой ситуации. Основной целью нашего проекта является помощь в защите ваших прав. Наши специалисты позаботятся о том, чтобы вы могли защитить свои интересы в любой проблемной ситуации. Мы предоставляем актуальную юридическую информацию по вопросам жилищного и земельного права, разделу имущества и алиментам, наследству, опеке и усыновлению. Если ваши права нарушены, специалисты нашего сайта всегда придут на помощь. Мы готовы оказать вам юридическую поддержку онлайн или по телефону в круглосуточном режиме.

  15. This is undoubtedly one of the greatest articles I’ve read on this topic! The author’s comprehensive knowledge and zeal for the subject shine through in every paragraph. I’m so appreciative for coming across this piece as it has enhanced my knowledge and sparked my curiosity even further. Thank you, author, for dedicating the time to produce such a outstanding article!

  16. Great work! This is the type of information that should be shared around the web. Shame on Google for not positioning this post higher! Come on over and visit my website . Thanks =)

  17. I should say also believe that mesothelioma cancer is a scarce form of cancers that is generally found in people previously exposed to asbestos. Cancerous cells form in the mesothelium, which is a protective lining which covers almost all of the body’s internal organs. These cells ordinarily form inside the lining with the lungs, abdomen, or the sac that really encircles one’s heart. Thanks for expressing your ideas.

  18. A few things i have constantly told people today is that while searching for a good on the net electronics retail outlet, there are a few variables that you have to factor in. First and foremost, you would like to make sure to find a reputable along with reliable retailer that has gotten great testimonials and ratings from other buyers and marketplace professionals. This will ensure that you are dealing with a well-known store that delivers good assistance and support to their patrons. Many thanks sharing your thinking on this website.

  19. whoah this blog is excellent i love reading your posts. Keep up the great work! You know, many people are hunting around for this info, you can help them greatly.

  20. JimmyHab表示:

    Адвокаты Москвы
    132 статья
    Мы успешно защищаем права и свободы юридических и физических лиц. Колоссальный и зачастую уникальный опыт, а также высокая квалификация наших сотрудников позволяют нам достигать результата, в максимальной степени отвечающего интересам клиента. Наши специалисты состоят в адвокатской палате которая на сегодняшний день является наиболее авторитетной в России. Благодаря многочленным блистательным победам в громких и, по мнению многих, бесперспективных делах, наши сотрудники снискали уважение не только в РФ, но и за рубежом.
    Если вам нужен адвокат в Москве просто обратитесь к нам и вы получите квалифицированную помощь в решении ваших проблем. Как показывает практика, в большинстве дел, в которых принимали участие наши адвокаты, суд выносил решение в пользу их клиентов. Кроме того, мы осуществляем страхование своей ответственности на 5 млн рублей. Такие гарантии вам не предложит ни одна юридическая компания.

    Стоит отметить, что за все то время, что работает наша компания не было прецедента, когда в результате действий наших специалистов клиенту был бы нанесен ущерб и возникла необходимость в страховой поддержке.

    Адвокатские услуги
    Адвокаты и юристы Москвы оказывают услуги в различных областях права: гражданского, арбитражного, уголовного и др. Нашими клиентами являются жители как столицы, так и других городов России. Для решения задач, которые стоят перед нашим клиентом, мы готовы оказать разовую помощь правового характера или сотрудничать на постоянной основе.

  21. I know this if off topic but I’m looking into starting my own blog and was wondering what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web savvy so I’m not 100 positive. Any tips or advice would be greatly appreciated. Many thanks

  22. Hello There. I found your blog using msn. This is an extremely well written article. I will make sure to bookmark it and return to read more of your useful information. Thanks for the post. I?ll definitely return.

  23. Thanks for another magnificent article. Where else could anybody get that kind of info in such an ideal way of writing? I’ve a presentation next week, and I am on the look for such information.

  24. Thanks for the diverse tips contributed on this blog site. I have observed that many insurance agencies offer customers generous discounts if they favor to insure multiple cars with them. A significant quantity of households currently have several automobiles these days, specially those with more mature teenage children still located at home, as well as savings upon policies might soon increase. So it is a good idea to look for a bargain.

  25. I’ve learned some important things through your post. I’d also like to convey that there is a situation in which you will make application for a loan and don’t need a co-signer such as a Federal government Student Support Loan. But when you are getting credit through a traditional bank or investment company then you need to be made ready to have a cosigner ready to help you. The lenders are going to base their own decision on the few elements but the greatest will be your credit standing. There are some loan companies that will as well look at your work history and make up your mind based on this but in many instances it will be based on on your scores.

  26. My brother recommended I would possibly like this website. He was entirely right. This post truly made my day. You cann’t imagine simply how much time I had spent for this info! Thanks!

  27. vk porn hup表示:

    Thank you a lot for sharing this with all of us you really realize what you’re talking approximately! Bookmarked. Please additionally visit my web site =). We could have a link change contract among us!

  28. Excellent goods from you, man. I’ve be mindful your stuff prior to and you are just extremely great. I really like what you’ve obtained here, certainly like what you are stating and the best way during which you are saying it. You’re making it entertaining and you continue to take care of to stay it sensible. I cant wait to learn much more from you. That is really a terrific web site.

  29. I just could not depart your web site prior to suggesting that I actually enjoyed the standard information a person provide for your visitors? Is gonna be back often in order to check up on new posts

發佈留言

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