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

  1. Thanks for your posting on the travel industry. I would also like to add that if you’re a senior thinking about traveling, it’s absolutely important to buy travel cover for retirees. When traveling, senior citizens are at high risk being in need of a healthcare emergency. Having the right insurance cover package for the age group can protect your health and give you peace of mind.

  2. I appreciate, lead to I discovered exactly what I used to be taking a look for. You’ve ended my four day lengthy hunt! God Bless you man. Have a great day. Bye

  3. Excellent post. I was checking continuously this blog and I am impressed! Extremely useful info specially the last part 🙂 I care for such info much. I was looking for this particular information for a very long time. Thank you and best of luck.

  4. Pretty section of content. I just stumbled upon your blog and in accession capital to assert that I acquire in fact loved account your weblog posts. Any way I?ll be subscribing to your augment and even I achievement you access constantly rapidly.

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

  6. One thing I’ve noticed is the fact there are plenty of misconceptions regarding the banking institutions intentions whenever talking about foreclosures. One fable in particular is the fact that the bank would like your house. The lender wants your dollars, not your property. They want the funds they lent you with interest. Avoiding the bank will only draw any foreclosed summary. Thanks for your post.

  7. Wubvxg表示:

    order hydroxyurea online cheap – ethionamide uk methocarbamol cost

  8. Useful information. Lucky me I found your site by chance, and I’m surprised why this coincidence did not happened earlier! I bookmarked it.

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

  10. Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an e-mail. I’ve got some creative ideas for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it improve over time.

  11. I do agree with all of the ideas you’ve presented in your post. They’re really convincing and will definitely work. Still, the posts are very short for newbies. Could you please extend them a bit from next time? Thanks for the post.

  12. This article is a breath of fresh air! The author’s unique perspective and insightful analysis have made this a truly engrossing read. I’m appreciative for the effort she has put into producing such an informative and mind-stimulating piece. Thank you, author, for offering your expertise and stimulating meaningful discussions through your outstanding writing!

  13. I used to be recommended this website through my cousin. I am no longer sure whether this submit is written through him as nobody else understand such special approximately my trouble. You are incredible! Thanks!

  14. One more thing. I believe that there are many travel insurance websites of respectable companies that permit you to enter holiday details and acquire you the prices. You can also purchase this international travel insurance policy online by using your current credit card. All you should do is usually to enter your current travel information and you can understand the plans side-by-side. Simply find the package that suits your finances and needs then use your credit card to buy the item. Travel insurance on the web is a good way to search for a dependable company pertaining to international holiday insurance. Thanks for revealing your ideas.

  15. A few things i have observed in terms of pc memory is always that there are specifications such as SDRAM, DDR and many others, that must fit the requirements of the motherboard. If the personal computer’s motherboard is very current and there are no main system issues, changing the storage space literally requires under an hour or so. It’s one of many easiest laptop upgrade treatments one can visualize. Thanks for discussing your ideas.

  16. Thanks for the tips you have discussed here. Moreover, I believe there are several factors which will keep your insurance premium down. One is, to consider buying cars that are from the good report on car insurance companies. Cars which might be expensive are definitely more at risk of being lost. Aside from that insurance policies are also in line with the value of the car, so the more costly it is, then higher this premium you pay.

  17. Thx for your post. I want to comment that the tariff of car insurance differs from one plan to another, simply because there are so many different facets which contribute to the overall cost. Such as, the model and make of the vehicle will have an enormous bearing on the purchase price. A reliable outdated family automobile will have a lower priced premium than the usual flashy sports car.

  18. nosso rateio表示:

    I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a developer to create your theme? Outstanding work!

  19. Thanks for your write-up. I also believe laptop computers have grown to be more and more popular lately, and now in many cases are the only sort of computer included in a household. Simply because at the same time potentially they are becoming more and more cost-effective, their working power is growing to the point where there’re as effective as pc’s coming from just a few years back.

  20. Also a thing to mention is that an online business administration program is designed for students to be able to smoothly proceed to bachelor’s degree programs. The Ninety credit certification meets the lower bachelor diploma requirements and when you earn the associate of arts in BA online, you’ll have access to the most recent technologies with this field. Several reasons why students have to get their associate degree in business is because they’re interested in this area and want to have the general schooling necessary just before jumping to a bachelor diploma program. Thanks for the tips you really provide with your blog.

  21. I have seen that nowadays, more and more people are increasingly being attracted to camcorders and the field of picture taking. However, being photographer, you should first invest so much time period deciding the exact model of camera to buy along with moving store to store just so you can buy the cheapest camera of the trademark you have decided to choose. But it will not end right now there. You also have to contemplate whether you should obtain a digital digital camera extended warranty. Thanks alot : ) for the good points I gathered from your blog site.

  22. I do enjoy the manner in which you have framed this problem plus it does supply me personally some fodder for consideration. Nonetheless, because of everything that I have personally seen, I basically trust when the actual comments pile on that individuals stay on point and don’t embark upon a tirade involving some other news of the day. Yet, thank you for this fantastic point and while I can not necessarily go along with the idea in totality, I respect your viewpoint.

  23. I like what you guys are up also. Such clever work and reporting! Carry on the excellent works guys I?ve incorporated you guys to my blogroll. I think it will improve the value of my web site 🙂

  24. rateio barato表示:

    Hi there! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

  25. Wow, amazing blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is excellent, as well as the content!

  26. Interesting article. It is extremely unfortunate that over the last decade, the travel industry has had to take on terrorism, SARS, tsunamis, bird flu, swine flu, plus the first ever entire global economic depression. Through it all the industry has really proven to be sturdy, resilient and dynamic, discovering new methods to deal with hardship. There are often fresh issues and opportunities to which the field must again adapt and act in response.

  27. Активируйте путь к лучшей версии себя – кликните по линку на кружок по психологии для старшеклассников

  28. Hi, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of
    spam comments? If so how do you protect against it,
    any plugin or anything you can recommend?
    I get so much lately it’s driving me mad so any assistance
    is very much appreciated.

發佈留言

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