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

32,434 Responses

  1. One thing I want to say is the fact before purchasing more laptop or computer memory, look into the machine directly into which it could be installed. Should the machine can be running Windows XP, for instance, a memory threshold is 3.25GB. Applying greater than this would simply constitute some sort of waste. Make sure one’s motherboard can handle your upgrade quantity, as well. Great blog post.

  2. Jamesavata表示:

    пин ап вход – пин ап вход

  3. Williamuniot表示:

    пин ап вход – пинап казино

  4. Jamesavata表示:

    пин ап казино – пин ап

  5. Dwayneseisa表示:

    kamagra jelly kopen kamagra jelly kopen Kamagra Kopen

  6. Williamuniot表示:

    пин ап – пин ап

  7. cat368win表示:

    Great article. It’s very unfortunate that over the last one decade, the travel industry has already been able to to take on terrorism, SARS, tsunamis, bird flu, swine flu, along with the first ever entire global downturn. Through all this the industry has proven to be powerful, resilient along with dynamic, obtaining new approaches to deal with adversity. There are continually fresh troubles and possibilities to which the marketplace must once again adapt and respond.

  8. cat368win表示:

    I am not certain the place you are getting your information, however good topic. I must spend some time learning more or working out more. Thanks for fantastic info I was on the lookout for this information for my mission.

  9. Dwayneseisa表示:

    kamagra pillen kopen kamagra 100mg kopen kamagra kopen nederland

  10. JesseDex表示:

    пин ап казино зеркало: https://pinupkz.life/

  11. I like the valuable info you provide in your articles. I will bookmark your weblog and check again here regularly. I am quite certain I?ll learn lots of new stuff right here! Best of luck for the next!

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

  13. Williamuniot表示:

    pinup 2025 – пин ап казино официальный сайт

  14. Hi, I think your website might be having browser compatibility issues. When I look at your blog in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, superb blog!

  15. Would you be inquisitive about exchanging hyperlinks?

  16. cat368win表示:

    I can’t express how much I value the effort the author has put into producing this outstanding piece of content. The clarity of the writing, the depth of analysis, and the wealth of information offered are simply impressive. His enthusiasm for the subject is obvious, and it has certainly resonated with me. Thank you, author, for providing your knowledge and enlightening our lives with this extraordinary article!

  17. Williamuniot表示:

    пин ап зеркало – пин ап

  18. JesseDex表示:

    пин ап казино: https://pinupkz.life/

  19. Dwayneseisa表示:

    Officiele Kamagra van Nederland kamagra jelly kopen kamagra pillen kopen

  20. Williamuniot表示:

    пин ап зеркало – пин ап казино официальный сайт

  21. huvip88表示:

    I think one of your advertisements caused my web browser to resize, you may well want to put that on your blacklist.

  22. Jamesavata表示:

    пин ап зеркало – пин ап

  23. Another thing is that when looking for a good on-line electronics shop, look for web shops that are constantly updated, always keeping up-to-date with the most recent products, the very best deals, along with helpful information on goods and services. This will make sure that you are dealing with a shop that stays atop the competition and give you what you should need to make knowledgeable, well-informed electronics buys. Thanks for the crucial tips I have really learned through your blog.

  24. Hey there! Someone in my Myspace group shared this website with us so I came to check it out. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Terrific blog and outstanding design.

  25. Cwpktn表示:

    buy cheap cytotec – cytotec 200mcg uk cost diltiazem 180mg

  26. Dwayneseisa表示:

    kamagra pillen kopen kamagra 100mg kopen kamagra jelly kopen

  27. Jamesavata表示:

    пин ап вход – пин ап

  28. Thanks for the thoughts you write about through this web site. In addition, several young women which become pregnant tend not to even try to get health insurance because they fear they wouldn’t qualify. Although many states today require that insurers supply coverage regardless of pre-existing conditions. Rates on most of these guaranteed options are usually higher, but when considering the high cost of health care it may be some sort of a safer way to go to protect the financial future.

  29. TracyRak表示:

    AquaSculpt weight loss is here to stay! With AquaSculpt capsules, you get fast AquaSculpt results thanks to natural AquaSculpt ingredients. No worries about AquaSculpt side effects—users confirm it in AquaSculpt reviews. Curious AquaSculpt how to use? It’s easy and effective. AquaSculpt where to buy? Visit http://aquasculpt.me and transform your body now!

發佈留言

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