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

  1. Georgedrync表示:

    cialis 5mg no perscription: cialis without a doctor prescription – cialis great price

  2. I do love the way you have presented this particular difficulty plus it does supply me personally some fodder for consideration. Nonetheless, coming from what I have personally seen, I basically hope when the comments pile on that individuals continue to be on issue and don’t start upon a tirade involving some other news of the day. Anyway, thank you for this exceptional point and although I can not necessarily agree with this in totality, I respect the perspective.

  3. Thanks for the thoughts you have discussed here. Also, I believe there are some factors which really keep your car insurance premium straight down. One is, to take into account buying vehicles that are inside the good listing of car insurance organizations. Cars which can be expensive are definitely more at risk of being lost. Aside from that insurance is also depending on the value of your vehicle, so the higher in price it is, then higher the actual premium you only pay.

  4. Georgedrync表示:

    canadian viagra: Cheap generic Viagra – viagra price

  5. Treffma表示:

    Здравствуйте!
    Как приобрести аттестат о среднем образовании в Москве и других городах
    diploms-man.ru/kupit-diplom-sssr
    Поможем вам всегда!.

  6. Great paintings! That is the kind of information that are meant to be shared across the internet. Shame on Google for not positioning this publish higher! Come on over and seek advice from my website . Thanks =)

  7. Thanks for the ideas you share through this web site. In addition, numerous young women that become pregnant tend not to even try to get health insurance because they have anxiety they couldn’t qualify. Although a lot of states now require that insurers give coverage irrespective of the pre-existing conditions. Rates on these kinds of guaranteed plans are usually higher, but when taking into consideration the high cost of medical care it may be any safer way to go to protect a person’s financial future.

  8. Diplomi_poEa表示:

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

  9. lady atom vk表示:

    I get pleasure from, result in I discovered exactly what I used to be looking for. You’ve ended my four day lengthy hunt! God Bless you man. Have a great day. Bye

  10. Mazrsqn表示:

    Привет, друзья!
    Как официально купить аттестат 11 класса с упрощенным обучением в Москве
    rushkadiplomik.ru

  11. Hello! I’ve been following your website for a while now and finally got the bravery to go ahead and give you a shout out from Lubbock Texas! Just wanted to mention keep up the great work!

  12. I appreciate, cause I found exactly what I was looking for. You’ve ended my 4 day long hunt! God Bless you man. Have a great day. Bye

  13. Many thanks for sharing these kind of wonderful blogposts. In addition, the ideal travel in addition to medical insurance plan can often eliminate those worries that come with vacationing abroad. A new medical emergency can quickly become too expensive and that’s sure to quickly put a financial stress on the family finances. Putting in place the suitable travel insurance program prior to setting off is definitely worth the time and effort. Cheers

  14. wonderful post, very informative. I wonder why the other experts of this sector don’t notice this. You must continue your writing. I’m sure, you’ve a great readers’ base already!

  15. you are really a good webmaster. The web site loading speed is amazing. It seems that you are doing any unique trick. Also, The contents are masterpiece. you have done a excellent job on this topic!

  16. Have you ever considered about including a little bit more than just your articles? I mean, what you say is fundamental and all. However think of if you added some great photos or video clips to give your posts more, “pop”! Your content is excellent but with images and videos, this blog could certainly be one of the very best in its field. Very good blog!

  17. I’m amazed by the quality of this content! The author has undoubtedly put a great amount of effort into researching and organizing the information. It’s refreshing to come across an article that not only offers helpful information but also keeps the readers captivated from start to finish. Great job to him for creating such a masterpiece!

  18. Feel free to visit my homepage – socialistener.com

  19. Samueldub表示:

    http://tadalafil.auction/# discount cialis

  20. I do like the way you have framed this particular challenge and it does offer me personally a lot of fodder for consideration. However, through just what I have witnessed, I simply just hope when the opinions stack on that people today stay on point and don’t get started on a tirade of the news of the day. Anyway, thank you for this excellent piece and although I do not necessarily agree with it in totality, I value your standpoint.

  21. Samueldub表示:

    https://sildenafil.llc/# viagra coupons

  22. you are in point of fact a excellent webmaster. The web site loading pace is incredible. It seems that you are doing any unique trick. Also, The contents are masterpiece. you have performed a fantastic activity in this matter!

  23. This is a great blog, would you be involved in doing an interview about how you created it? If so e-mail me!

  24. I believe that avoiding refined foods may be the first step to lose weight. They can taste fine, but prepared foods have got very little vitamins and minerals, making you try to eat more in order to have enough energy to get with the day. If you are constantly consuming these foods, changing to cereals and other complex carbohydrates will aid you to have more vigor while consuming less. Good blog post.

  25. Georgedrync表示:

    viagra coupon: buy sildenafil online usa – 100 mg viagra lowest price

  26. We stumbled over here from a different page and thought I may as well check things out. I like what I see so now i’m following you. Look forward to checking out your web page again.

  27. Whitescreen65表示:

    Hello there, I discovered your blog via Google at the same time as searching for a related subject, your website got here up, it seems good. I’ve bookmarked it in my google bookmarks.

  28. Samueldub表示:

    http://tadalafil.auction/# cialis from china

  29. Whitescreen70表示:

    It is perfect time to make a few plans for the long run and it’s time to be happy. I’ve read this publish and if I could I want to suggest you few fascinating issues or suggestions. Maybe you could write next articles relating to this article. I desire to learn more things approximately it!

發佈留言

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