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

  1. Thanks for your write-up. Another item is that being a photographer consists of not only trouble in catching award-winning photographs but additionally hardships in acquiring the best digital camera suited to your requirements and most especially challenges in maintaining the caliber of your camera. This is very correct and obvious for those photography lovers that are straight into capturing the actual nature’s eye-catching scenes : the mountains, the forests, the wild or the seas. Going to these exciting places certainly requires a camera that can live up to the wild’s nasty environments.

  2. Thanks for this article. I’d personally also like to talk about the fact that it can end up being hard while you are in school and simply starting out to initiate a long credit standing. There are many scholars who are simply trying to make it and have a long or favourable credit history can be a difficult matter to have.

  3. The term ‘big data’ is usually used to refer to massive, rapidly expanding, varied and often unstructured sets of digitized data that are difficult to maintain using traditional databases.

  4. I think other web site proprietors should take this site as an model, very clean and great user genial style and design, as well as the content. You are an expert in this topic!

  5. Income settlement incorporates exchange of the spot cost variation of the workout price tag and the commodity, depending on the future contracts.

  6. Thanks for your article. I would love to say that your health insurance agent also works best for the benefit of the coordinators of a group insurance cover. The health insurance broker is given a summary of benefits sought by an individual or a group coordinator. Exactly what a broker may is find individuals as well as coordinators which best complement those wants. Then he shows his recommendations and if the two of you agree, the particular broker formulates a contract between the 2 parties.

  7. Good write-up, I am normal visitor of one?s site, maintain up the excellent operate, and It is going to be a regular visitor for a lengthy time.

  8. You really make it appear so easy along with your presentation however I find this topic to be actually something that I feel I might by no means understand. It seems too complex and very extensive for me. I’m taking a look forward to your next submit, I will try to get the grasp of it!

  9. A variable interest rate will change as these interest rates change, but a variable rate plan must also have a cap on how high the rate can go during the term of the plan.

  10. вывод из запоя в стационаре ростов вывод из запоя в стационаре ростов .

  11. For many traders, it makes sense to trade Bitcoin which is one of the many cryptocurrencies out there.

  12. I like the helpful information you provide on your articles. I?ll bookmark your blog and test again here frequently. I’m rather sure I?ll be told a lot of new stuff right here! Best of luck for the following!

  13. I have been surfing on-line more than three hours these days, but I by no means discovered any fascinating article like yours. It?s beautiful price sufficient for me. Personally, if all web owners and bloggers made good content material as you did, the web might be much more useful than ever before.

  14. Thank you, I’ve just been searching for information about this subject for ages and yours is the greatest I’ve discovered so far. But, what about the conclusion? Are you sure about the source?

  15. I?ve been exploring for a bit for any high quality articles or weblog posts in this kind of house . Exploring in Yahoo I eventually stumbled upon this site. Reading this info So i am happy to express that I have a very just right uncanny feeling I found out exactly what I needed. I such a lot indubitably will make certain to don?t disregard this website and give it a glance on a relentless basis.

  16. I love your wp template, exactly where did you download it through?

  17. The walls behind the shelves can be outfitted with pegboard to hold small bins and hooks so no space is wasted.

  18. Youre so cool! I dont suppose Ive learn anything like this before. So nice to search out any individual with some original thoughts on this subject. realy thank you for starting this up. this website is something that’s needed on the web, somebody with slightly originality. useful job for bringing one thing new to the web!

  19. The (RMS) considers significant or influential impact that may affect the company negatively or positively.

  20. Thank you for another informative website. Where else could I get that kind of info written in such an ideal way? I have a project that I am just now working on, and I have been on the look out for such information.

  21. Great blog post. Some tips i would like to bring up is that personal computer memory is required to be purchased if your computer can no longer cope with that which you do with it. One can deploy two RAM memory boards with 1GB each, in particular, but not certainly one of 1GB and one with 2GB. One should always check the manufacturer’s documentation for own PC to ensure what type of storage it can take.

  22. DanielTet表示:

    buy cytotec over the counter https://furosemide.win/# lasix 20 mg
    lasix 20 mg

  23. Thanks a lot for your post. I’d like to write my opinion that the tariff of car insurance will vary from one insurance plan to another, due to the fact there are so many different facets which bring about the overall cost. As an example, the make and model of the motor vehicle will have an enormous bearing on the fee. A reliable outdated family vehicle will have a more economical premium over a flashy expensive car.

  24. Interesting article. It is extremely unfortunate that over the last 10 years, the travel industry has already been able to to deal with terrorism, SARS, tsunamis, bird flu, swine flu, as well as the first ever entire global tough economy. Through everthing the industry has really proven to be powerful, resilient in addition to dynamic, locating new tips on how to deal with adversity. There are always fresh issues and chance to which the marketplace must just as before adapt and respond.

  25. Hey! Would you mind if I share your blog with my myspace group? There’s a lot of people that I think would really enjoy your content. Please let me know. Many thanks

  26. Greetings! I’ve been following your site for a while now and finally got the courage to go ahead and give you a shout out from Houston Tx! Just wanted to mention keep up the fantastic job!

  27. You could definitely see your enthusiasm in the work you write. The world hopes for more passionate writers like you who are not afraid to say how they believe. Always follow your heart.

發佈留言

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