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

  1. Greetings from Florida! I’m bored to tears at work so I decided to browse your blog on my iphone during lunch break. I love the information you present here and can’t wait to take a look when I get home. I’m shocked at how quick your blog loaded on my phone .. I’m not even using WIFI, just 3G .. Anyways, great site!

  2. great issues altogether, you just received a new reader. What might you recommend in regards to your publish that you simply made a few days ago? Any positive?

  3. Great goods from you, man. I’ve understand your stuff previous to and you are just extremely fantastic. I actually like what you’ve acquired here, really like what you are saying and the way in which you say it. You make it entertaining and you still take care of to keep it sensible. I can’t wait to read far more from you. This is actually a wonderful website.

  4. Wow! This can be one particular of the most beneficial blogs We’ve ever arrive across on this subject. Basically Great. I’m also a specialist in this topic therefore I can understand your effort.

  5. ro server表示:

    Excellent post but I was wanting to know if you could write a litte more on this topic? I’d be very thankful if you could elaborate a little bit more. Kudos!

  6. I’ve been surfing on-line more than three hours today, but I by no means found any fascinating article like yours. It is lovely worth sufficient for me. In my view, if all site owners and bloggers made good content material as you probably did, the web will be much more useful than ever before.

  7. wonderful publish, very informative. I ponder why the opposite specialists of this sector don’t notice this. You should proceed your writing. I am confident, you have a huge readers’ base already!

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

  9. I have been exploring for a little bit for any high quality articles or blog posts on this kind of area . Exploring in Yahoo I at last stumbled upon this website. Reading this information So i am happy to convey that I have an incredibly good uncanny feeling I discovered exactly what I needed. I most certainly will make sure to do not forget this web site and give it a look regularly.

  10. Thank you for the good writeup. It in reality was once a leisure account it. Look advanced to far delivered agreeable from you! However, how can we keep in touch?

  11. The subsequent time I read a blog, I hope that it doesnt disappoint me as a lot as this one. I imply, I know it was my choice to read, but I truly thought youd have one thing interesting to say. All I hear is a bunch of whining about something that you could fix in the event you werent too busy in search of attention.

  12. I’m often to blogging and i actually respect your content. The article has really peaks my interest. I’m going to bookmark your web site and keep checking for new information.

  13. Good blog post. Some tips i would like to bring up is that computer memory ought to be purchased but if your computer still cannot cope with whatever you do along with it. One can deploy two random access memory boards of 1GB each, by way of example, but not certainly one of 1GB and one of 2GB. One should check the company’s documentation for one’s PC to ensure what type of storage is necessary.

  14. I do enjoy the manner in which you have framed this specific challenge plus it does indeed supply me personally a lot of fodder for consideration. Nonetheless, because of everything that I have witnessed, I simply just trust when the comments stack on that folks stay on issue and not get started on a tirade involving some other news du jour. Still, thank you for this exceptional point and while I do not necessarily concur with it in totality, I respect your standpoint.

  15. Thanks for the points you have shared here. Another thing I would like to convey is that pc memory specifications generally go up along with other improvements in the technological innovation. For instance, as soon as new generations of processors are made in the market, there is certainly usually a matching increase in the size preferences of both the laptop memory and hard drive space. This is because the program operated simply by these cpus will inevitably boost in power to make new know-how.

  16. Lazrxxj表示:

    Привет, друзья!
    Мы изготавливаем дипломы любых профессий по доступным тарифам.
    lanouvellemine.fr/купить-диплом-новосибирск/

  17. There are some attention-grabbing time limits on this article however I don?t know if I see all of them center to heart. There’s some validity but I’ll take hold opinion until I look into it further. Good article , thanks and we wish more! Added to FeedBurner as effectively

  18. Great ? I should definitely pronounce, impressed with your web site. I had no trouble navigating through all tabs as well as 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. Quite unusual. Is likely to appreciate it for those who add forums or anything, web site theme . a tones way for your customer to communicate. Nice task..

  19. JamesBak表示:

    cipro online no prescription in the usa: buy ciprofloxacin – ciprofloxacin

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

  21. Cazrqtl表示:

    Привет!
    Мы готовы предложить документы ВУЗов, расположенных на территории всей России. Вы сможете приобрести качественно напечатанный диплом за любой год, указав актуальную специальность и оценки за все дисциплины. Дипломы и аттестаты печатаются на бумаге высшего качества. Это позволяет делать настоящие дипломы, не отличимые от оригиналов. Они заверяются всеми требуемыми печатями и штампами.
    http://www.b2bempowerment.org/blogs/397/%D0%91%D1%8B%D1%81%D1%82%D1%80%D0%BE-%D0%B7%D0%B0%D0%BA%D0%B0%D0%B7%D1%8B%D0%B2%D0%B0%D0%B5%D0%BC-%D0%B4%D0%BE%D0%BA%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D0%B2-%D0%B8%D0%BD%D1%82%D0%B5%D1%80%D0%BD%D0%B5%D1%82-%D0%BC%D0%B0%D0%B3%D0%B0%D0%B7%D0%B8%D0%BD%D0%B5-Russian-Diplom

  22. You can definitely see your expertise in the work you write. The world hopes for even more passionate writers like you who aren’t afraid to say how they believe. Always follow your heart.

  23. Hello just wanted to give you a quick heads up. The words in your article seem to be running off the screen in Opera. I’m not sure if this is a formatting issue or something to do with browser compatibility but I thought I’d post to let you know. The design look great though! Hope you get the problem solved soon. Many thanks

  24. Xazrihl表示:

    Привет!
    Как оказалось, купить диплом кандидата наук не так уж и сложно
    arusak-diploms-srednee.ru/kupit-diplom-v-krasnodare В 

  25. I just added this webpage to my rss reader, excellent stuff. Can’t get enough!

  26. Excellent goods from you, man. I’ve understand your stuff previous to and you’re just too magnificent. I actually like what you have acquired here, really like what you are saying and the way in which you say it. You make it enjoyable and you still care for to keep it sensible. I can not wait to read far more from you. This is actually a terrific site.

  27. Nearly all of the things you state happens to be supprisingly appropriate and it makes me wonder why I had not looked at this in this light before. Your article really did switch the light on for me as far as this specific issue goes. However there is 1 point I am not necessarily too comfortable with so while I try to reconcile that with the central theme of your position, permit me see exactly what the rest of the visitors have to say.Nicely done.

  28. Hi there would you mind sharing which blog platform you’re using? I’m planning to start my own blog in the near future but I’m having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something unique. P.S Sorry for getting off-topic but I had to ask!

  29. you are really a good webmaster. The site loading speed is incredible. It seems that you are doing any unique trick. Moreover, The contents are masterwork. you’ve done a magnificent job on this topic!

  30. Mazrxhg表示:

    Здравствуйте!
    Легальные способы покупки диплома о среднем полном образовании
    myworldavto.ru/legkiy-sposob-poluchit-diplom-onlayn

發佈留言

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