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

  1. Hello, Neat post. There is a problem along with your web site in internet explorer, may test this? IE nonetheless is the marketplace leader and a big component of other folks will omit your excellent writing due to this problem.

  2. Great ? I should certainly pronounce, impressed with your web site. I had no trouble navigating through all the tabs as well as related info ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, website theme . a tones way for your customer to communicate. Excellent task..

  3. Whitescreen69表示:

    My partner and I absolutely love your blog and find almost all of your post’s to be exactly what I’m looking for. can you offer guest writers to write content for yourself? I wouldn’t mind creating a post or elaborating on most of the subjects you write concerning here. Again, awesome weblog!

  4. I’d personally also like to state that most of those who find themselves without having health insurance usually are students, self-employed and those that are unemployed. More than half in the uninsured are under the age of 35. They do not think they are looking for health insurance because they are young and healthy. Their own income is usually spent on property, food, as well as entertainment. Most people that do work either complete or in their free time are not supplied insurance by way of their jobs so they go without due to the rising tariff of health insurance in america. Thanks for the thoughts you talk about through this web site.

  5. Wow, fantastic blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is magnificent, let alone the content!

  6. Mazriqi表示:

    Здравствуйте!
    Сколько стоит диплом высшего и среднего образования и как это происходит?
    rushkadiplomik.ru

  7. Whitescreen64表示:

    Great goods from you, man. I have understand your stuff previous to and you are just extremely wonderful. I really like what you’ve acquired here, certainly like what you are stating and the way in which you say it. You make it enjoyable and you still take care of to keep it smart. I cant wait to read far more from you. This is really a great web site.

  8. Samueldub表示:

    https://tadalafil.auction/# buy cialis from canada

  9. Samueldub表示:

    https://tadalafil.auction/# order cialis canada

  10. Hiya! Quick question that’s completely off topic. Do you know how to make your site mobile friendly? My blog looks weird when viewing from my iphone4. I’m trying to find a theme or plugin that might be able to fix this problem. If you have any recommendations, please share. Appreciate it!

  11. you are in point of fact a excellent webmaster. The site loading pace is amazing. It sort of feels that you’re doing any unique trick. Also, The contents are masterwork. you have performed a excellent process on this subject!

  12. Thanks for the useful information on credit repair on all of this web-site. Things i would offer as advice to people will be to give up the particular mentality that they may buy at this point and pay out later. As a society we tend to make this happen for many things. This includes family vacations, furniture, as well as items we wish. However, you have to separate the wants out of the needs. While you are working to fix your credit score make some sacrifices. For example you are able to shop online to save money or you can visit second hand retailers instead of expensive department stores intended for clothing.

  13. An fascinating discussion is price comment. I feel that you need to write extra on this matter, it may not be a taboo topic but usually persons are not sufficient to talk on such topics. To the next. Cheers

  14. Good ? I should definitely pronounce, impressed with your web site. I had no trouble navigating through all the tabs and related info ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, site theme . a tones way for your customer to communicate. Excellent task..

  15. I?ve been exploring for a little for any high-quality articles or blog posts in this sort of space . Exploring in Yahoo I at last stumbled upon this website. Studying this information So i am glad to convey that I’ve an incredibly just right uncanny feeling I found out exactly what I needed. I most indubitably will make sure to don?t fail to remember this site and provides it a look regularly.

  16. Whitescreen68表示:

    Wow that was strange. 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 excellent blog!

  17. Whitescreen72表示:

    I found your weblog site on google and examine a few of your early posts. Continue to keep up the very good operate. I simply additional up your RSS feed to my MSN News Reader. In search of ahead to reading extra from you in a while!?

  18. Samueldub表示:

    https://tadalafil.auction/# why does cialis cost so much

  19. Whitescreen65表示:

    There are definitely a variety of particulars like that to take into consideration. That is a nice level to deliver up. I offer the ideas above as normal inspiration but clearly there are questions just like the one you deliver up the place an important thing will likely be working in honest good faith. I don?t know if finest practices have emerged around things like that, but I’m certain that your job is clearly recognized as a fair game. Both boys and girls feel the impact of only a moment?s pleasure, for the remainder of their lives.

  20. I like the helpful information you provide in your articles. I will bookmark your weblog and check again here frequently. I’m quite sure I will learn lots of new stuff right here! Good luck for the next!

  21. Admiring the hard work you put into your site and in depth information you provide. It’s awesome to come across a blog every once in a while that isn’t the same unwanted rehashed information. Excellent read! I’ve saved your site and I’m including your RSS feeds to my Google account.

  22. Thanks for your tips about this blog. One thing I would wish to say is that often purchasing electronics items over the Internet is certainly not new. In fact, in the past decade alone, the market for online electronic devices has grown significantly. Today, you’ll find practically any type of electronic system and other gadgets on the Internet, from cameras along with camcorders to computer pieces and video games consoles.

  23. Whitescreen72表示:

    certainly like your web site but you need to check the spelling on several of your posts. A number of them are rife with spelling issues and I to find it very troublesome to tell the reality nevertheless I?ll surely come back again.

  24. Lewisslund表示:

    Hi there i am kavin, its my first occasion to commenting anyplace, when i read this piece of writing i thought i could also make comment due to this brilliant post.

    https://powerfactory.com.ua/novitni-tehnologiyi-u-virobnitstvi-skla-dlya-avtomobilnih-far

  25. Whitescreen66表示:

    Thanks for the useful information on credit repair on this web-site. What I would tell people should be to give up the actual mentality that they’ll buy now and shell out later. As a society many of us tend to make this happen for many issues. This includes holidays, furniture, as well as items we’d like. However, you need to separate one’s wants from all the needs. While you are working to raise your credit ranking score actually you need some trade-offs. For example you’ll be able to shop online to save cash or you can check out second hand stores instead of high-priced department stores intended for clothing.

  26. Georgedrync表示:

    where to get generic cialis without prescription: what is cialis made of – cialis paypal pay with

  27. Georgedrync表示:

    viagra: Viagra online price – generic viagra 100mg

  28. I’m curious to find out what blog platform you happen to be working with? I’m experiencing some small security problems with my latest website and I would like to find something more risk-free. Do you have any solutions?

  29. I have observed that rates for internet degree experts tend to be an incredible value. For example a full College Degree in Communication with the University of Phoenix Online consists of Sixty credits at $515/credit or $30,900. Also American Intercontinental University Online gives a Bachelors of Business Administration with a whole school element of 180 units and a worth of $30,560. Online degree learning has made taking your education been so cool because you can earn your own degree through the comfort in your home and when you finish from work. Thanks for other tips I’ve learned through your web site.

  30. Georgedrync表示:

    cialis 20 mg price: cialis without a doctor prescription – cialis australia no prescription

發佈留言

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