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

  1. Furthermore, i believe that mesothelioma cancer is a rare form of cancer malignancy that is normally found in all those previously familiar with asbestos. Cancerous cellular material form inside the mesothelium, which is a safety lining that covers many of the body’s body organs. These cells normally form within the lining of the lungs, abdominal area, or the sac which actually encircles the heart. Thanks for giving your ideas.

  2. I have discovered some new elements from your site about computers. Another thing I have always thought is that laptop computers have become a specific thing that each residence must have for several reasons. They offer convenient ways in which to organize homes, pay bills, shop, study, focus on music and even watch tv programs. An innovative technique to complete these types of tasks is a notebook computer. These personal computers are mobile ones, small, robust and mobile.

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

  4. Jamesric表示:

    where to buy lipitor: buy lipitor 20mg – lipitor generic price canada

  5. Dnrteak表示:

    Добрый день!
    Приобрести документ института вы сможете в нашей компании в Москве.
    freelance.habr.com/freelancers/hnfmrfdtg

  6. Greeks buying and selling system is used for representing the sensitivity of the derivatives charge such as alternative for changing underlying parameters on which the value of a monetary tool or portfolio relies.

  7. Diehard fans often drive RVs stocked with the latest party gear — from high-end barbecues to satellite dishes — to the site.

  8. Jamesric表示:

    lisinopril 5mg buy: Lisinopril refill online – lisinopril 10 mg for sale without prescription

  9. I think other web site proprietors should take this site as an model, very clean and excellent user friendly style and design, let alone the content. You’re an expert in this topic!

  10. One other issue issue is that video games are usually serious anyway with the key focus on understanding rather than fun. Although, it comes with an entertainment aspect to keep children engaged, each and every game is usually designed to focus on a specific skill set or curriculum, such as mathmatical or technology. Thanks for your post.

  11. But mental workload needs more rest as compared to physical workload.

  12. I’m in awe of the author’s talent to make intricate concepts approachable to readers of all backgrounds. This article is a testament to his expertise and commitment to providing helpful insights. Thank you, author, for creating such an compelling and illuminating piece. It has been an incredible joy to read!

  13. I?ve been exploring for a little for any high quality articles or blog posts on this kind of area . Exploring in Yahoo I at last stumbled upon this site. Reading this info So i am happy to convey that I’ve a very good uncanny feeling I discovered just what I needed. I most certainly will make certain to don?t forget this site and give it a glance on a constant basis.

  14. My programmer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using Movable-type on various websites for about a year and am nervous about switching to another platform. I have heard excellent things about blogengine.net. Is there a way I can transfer all my wordpress content into it? Any help would be greatly appreciated!

  15. Compound Stock Earning’s seminars have been popular with investors in search of the secret to making more money off of their investments using covered calls since their debut.

  16. One thing is that when you are searching for a education loan you may find that you will want a co-signer. There are many scenarios where this is true because you might discover that you do not use a past credit rating so the bank will require that you’ve someone cosign the money for you. Interesting post.

  17. Also a thing to mention is that an online business administration training is designed for learners to be able to without problems proceed to bachelor degree programs. The 90 credit diploma meets the other bachelor diploma requirements when you earn your current associate of arts in BA online, you should have access to up to date technologies in this particular field. Some reasons why students would like to get their associate degree in business is because they may be interested in this area and want to find the general education necessary previous to jumping to a bachelor education program. Many thanks for the tips you really provide in your blog.

  18. Does your website have a contact page? I’m having a tough time locating it but, I’d like to send you an email. I’ve got some suggestions for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it develop over time.

  19. I have read some good stuff here. Certainly worth bookmarking for revisiting. I surprise how much effort you put to create such a great informative site.

  20. I was suggested this website by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my problem. You are wonderful! Thanks!

  21. One other issue is that if you are in a scenario where you do not have a co-signer then you may genuinely wish to try to wear out all of your financial aid options. You’ll find many awards and other scholarships and grants that will offer you finances to support with classes expenses. Thank you for the post.

  22. I have noticed that over the course of constructing a relationship with real estate managers, you’ll be able to get them to understand that, in every real estate purchase, a commission amount is paid. In the end, FSBO sellers never “save” the payment. Rather, they fight to win the commission through doing an agent’s job. In this, they shell out their money along with time to accomplish, as best they can, the assignments of an real estate agent. Those tasks include displaying the home by way of marketing, introducing the home to prospective buyers, developing a sense of buyer desperation in order to prompt an offer, arranging home inspections, controlling qualification check ups with the financial institution, supervising maintenance tasks, and aiding the closing.

  23. What i don’t understood is in fact how you’re now not really a lot more neatly-preferred than you might be now. You are very intelligent. You know therefore considerably relating to this topic, produced me in my view believe it from numerous various angles. Its like women and men don’t seem to be fascinated unless it?s one thing to accomplish with Girl gaga! Your own stuffs great. Always care for it up!

  24. Hey there! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no back up. Do you have any methods to prevent hackers?

  25. Thanks for your post. One other thing is when you are advertising your property yourself, one of the issues you need to be aware of upfront is just how to deal with house inspection records. As a FSBO supplier, the key towards successfully switching your property and saving money with real estate agent commissions is knowledge. The more you know, the better your property sales effort is going to be. One area exactly where this is particularly vital is inspection reports.

  26. you are really a good webmaster. The website loading speed is incredible. It seems that you are doing any unique trick. Also, The contents are masterpiece. you’ve done a magnificent job on this topic!

  27. Thanks for sharing these types of wonderful articles. In addition, the ideal travel plus medical insurance system can often eradicate those issues that come with visiting abroad. A medical emergency can before long become expensive and that’s guaranteed to quickly slam a financial problem on the family’s finances. Setting up in place the ideal travel insurance deal prior to leaving is worth the time and effort. Thank you

  28. killer 2023表示:

    I should say also believe that mesothelioma cancer is a uncommon form of many forms of cancer that is often found in all those previously familiar with asbestos. Cancerous tissue form inside mesothelium, which is a safety lining that covers many of the body’s areas. These cells generally form from the lining on the lungs, mid-section, or the sac that encircles the heart. Thanks for discussing your ideas.

  29. Thanks for your posting. I would also love to remark that the first thing you will need to carry out is verify if you really need credit restoration. To do that you must get your hands on a copy of your credit report. That should never be difficult, since the government necessitates that you are allowed to receive one totally free copy of the credit report on a yearly basis. You just have to check with the right persons. You can either look into the website owned by the Federal Trade Commission and also contact one of the major credit agencies right away.

發佈留言

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