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...

15,962 Responses

  1. Wow, fantastic blog format! How long have you ever been blogging for? you made running a blog look easy. The full glance of your site is great, as smartly as the content!

  2. I have observed that expenses for on-line degree specialists tend to be a fantastic 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 comes with a Bachelors of Business Administration with a overall course feature of 180 units and a tuition fee of $30,560. Online studying has made obtaining your college degree much simpler because you can earn your own degree from the comfort of your abode and when you finish working. Thanks for all the other tips I have certainly learned through your blog.

  3. Heya just wanted to give you a brief heads up and let you know a few of the images aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different web browsers and both show the same outcome.

  4. Hiya, I’m really glad I’ve found this information. Today bloggers publish only about gossips and internet and this is actually irritating. A good blog with interesting content, this is what I need. Thank you for keeping this website, I will be visiting it. Do you do newsletters? Can’t find it.

  5. Hey! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly? My web site looks weird when browsing from my iphone. I’m trying to find a template or plugin that might be able to fix this issue. If you have any suggestions, please share. Cheers!

  6. You should take part in a contest for probably the greatest blogs on the web. I will suggest this site!

  7. An fascinating dialogue is worth comment. I feel that it is best to write more on this matter, it may not be a taboo subject but usually people are not sufficient to speak on such topics. To the next. Cheers

  8. I have recently started a web site, the info you offer on this web site has helped me tremendously. Thank you for all of your time & work.

  9. Hello would you mind letting me know which webhost you’re using? I’ve loaded your blog in 3 different web browsers and I must say this blog loads a lot faster then most. Can you suggest a good web hosting provider at a honest price? Thanks, I appreciate it!

  10. KevinSounc表示:

    https://slotsiteleri.bid/# en iyi slot siteleri

  11. I have realized that online degree is getting well-liked because getting your degree online has changed into a popular solution for many people. A huge number of people have certainly not had an opportunity to attend a traditional college or university however seek the elevated earning possibilities and career advancement that a Bachelor’s Degree offers. Still people might have a college degree in one course but would like to pursue anything they now develop an interest in.

  12. Howdy, i read your blog from time to time and i own a similar one and i was just curious if you get a lot of spam feedback? If so how do you reduce it, any plugin or anything you can suggest? I get so much lately it’s driving me insane so any assistance is very much appreciated.

  13. I have come to understand that service fees for online degree pros tend to be a fantastic value. Like a full Bachelor’s Degree in Communication from The University of Phoenix Online consists of 60 credits at $515/credit or $30,900. Also American Intercontinental University Online gives a Bachelors of Business Administration with a whole education course feature of 180 units and a tariff of $30,560. Online degree learning has made getting your higher education degree been so cool because you can certainly earn your degree from the comfort of your dwelling place and when you finish from work. Thanks for all your other tips I have learned through the web-site.

  14. I’ve learned some new things from a blog post. Yet another thing to I have noticed is that normally, FSBO sellers are going to reject people. Remember, they would prefer to never use your products and services. But if an individual maintain a comfortable, professional romance, offering help and remaining in contact for about four to five weeks, you will usually be capable to win interviews. From there, a listing follows. Thanks a lot

  15. Darrelherse表示:

    slot bahis siteleri: slot oyun siteleri – en yeni slot siteleri

  16. I have come across that now, more and more people are increasingly being attracted to video cameras and the subject of digital photography. However, being a photographer, you need to first shell out so much period deciding the model of photographic camera to buy and also moving store to store just so you could possibly buy the most affordable camera of the trademark you have decided to settle on. But it doesn’t end generally there. You also have to take into consideration whether you should obtain a digital digital camera extended warranty. Thanks for the good guidelines I received from your blog site.

  17. Things i have seen in terms of laptop memory is that there are technical specs such as SDRAM, DDR etc, that must go with the requirements of the mother board. If the computer’s motherboard is kind of current while there are no computer OS issues, modernizing the storage space literally takes under a couple of hours. It’s one of many easiest computer system upgrade types of procedures one can visualize. Thanks for sharing your ideas.

  18. Wow that was odd. I just wrote an extremely long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say excellent blog!

  19. I?m impressed, I have to say. Really not often do I encounter a weblog that?s each educative and entertaining, and let me inform you, you’ve hit the nail on the head. Your idea is excellent; the issue is something that not enough persons are speaking intelligently about. I am very pleased that I stumbled throughout this in my search for something regarding this.

  20. I do consider all of the concepts you’ve presented on your post. They’re really convincing and can definitely work. Still, the posts are very short for newbies. May you please extend them a little from subsequent time? Thanks for the post.

  21. Fantastic items from you, man. I’ve have in mind your stuff prior to and you’re just extremely wonderful. I really like what you have got right here, really like what you are stating and the best way by which you are saying it. You’re making it enjoyable and you continue to care for to stay it wise. I can’t wait to read far more from you. That is actually a terrific site.

  22. Spot on with this write-up, I truly think this website wants way more consideration. I?ll in all probability be once more to read way more, thanks for that info.

  23. I enjoy what you guys are usually up too. This type of clever work and exposure! Keep up the good works guys I’ve included you guys to blogroll.

  24. I?ve been exploring for a little bit for any high-quality articles or blog posts in this kind of area . Exploring in Yahoo I at last stumbled upon this web site. Studying this information So i am glad to exhibit that I’ve a very good uncanny feeling I found out just what I needed. I such a lot indisputably will make sure to do not disregard this web site and give it a glance on a continuing basis.

  25. Wow! I’m in awe of the author’s writing skills and talent to convey complicated concepts in a clear and clear manner. This article is a true gem that deserves all the praise it can get. Thank you so much, author, for providing your wisdom and giving us with such a valuable resource. I’m truly grateful!

  26. Magnificent items from you, man. I’ve remember your stuff previous to and you’re simply extremely fantastic. I actually like what you’ve bought here, really like what you are saying and the way in which through which you say it. You are making it entertaining and you still care for to keep it sensible. I can not wait to read much more from you. That is really a wonderful site.

  27. I think this is among the so much vital information for me. And i am happy studying your article. However want to remark on few general things, The site taste is great, the articles is really great : D. Good job, cheers

  28. whoah this blog is excellent i love reading your posts. Keep up the good work! You know, many people are searching around for this info, you could aid them greatly.

發佈留言

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