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

37,207 Responses

  1. Whereas understanding at a gym, died on May 11, 2001 of a coronary heart assault.

  2. Jasonzitte表示:

    Medicament prescribing information.
    can i get cheap clomid for sale
    The most pleasant pharmacy experience every time.

  3. Victorprima表示:

    Their international collaborations benefit patients immensely.
    can i get cipro pill
    A name synonymous with international pharmaceutical trust.

  4. Jasonzitte表示:

    The best place for quality health products.
    order clomid online
    Every pharmacist here is a true professional.

  5. An added important issue is that if you are a senior citizen, travel insurance with regard to pensioners is something you must really look at. The older you are, greater at risk you’re for getting something poor happen to you while in another country. If you are not covered by a few comprehensive insurance policy, you could have a number of serious troubles. Thanks for sharing your hints on this blog.

  6. 1win_gqor表示:

    один вин официальный сайт https://1win109.com.kg/ .

  7. Victorprima表示:

    A modern pharmacy with a traditional touch of care.
    is gabapentin scheduled
    Always stocked with the best brands.

  8. The following pages will look at how Hollywood accounting works, the forms of movies affected – and why the system is likely to persist.

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

  10. Victorprima表示:

    A pharmacy that takes pride in community service.
    to buy gabapentin 600 mg
    A pharmacy that genuinely cares about community well-being.

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

  12. Jasonzitte表示:

    Their international drug database is unparalleled.
    can i purchase cheap cytotec
    The best choice for personalized care.

  13. Jasonzitte表示:

    Long-Term Effects.
    how to buy generic cipro no prescription
    Their online refill system is straightforward.

  14. Another thing is that when you are evaluating a good internet electronics store, look for online shops that are consistently updated, preserving up-to-date with the latest products, the very best deals, in addition to helpful information on goods and services. This will make sure that you are handling a shop which stays ahead of the competition and give you what you need to make educated, well-informed electronics buying. Thanks for the critical tips I’ve learned from the blog.

  15. 1win_tvor表示:

    1win kg скачать http://1win109.com.kg .

  16. Victorprima表示:

    A pharmacy that breaks down international barriers.
    where to get cytotec without insurance
    They have a great selection of wellness products.

  17. Stewart, Jack. “How to fix a automobile — with out a mechanic.” BBC.

  18. Great blog here! Also your web site lots up fast! What web host are you the use of? Can I get your associate hyperlink to your host? I wish my website loaded up as quickly as yours lol

  19. Jasonzitte表示:

    Their senior citizen discounts are much appreciated.
    where can i get generic lisinopril for sale
    Their health and beauty section is fantastic.

  20. Victorprima表示:

    A one-stop-shop for all my health needs.
    can i get gabapentin
    A trusted name in international pharmacy circles.

  21. Jasonzitte表示:

    The free blood pressure check is a nice touch.
    can you get cheap cytotec without prescription
    The best choice for personalized care.

  22. Victorprima表示:

    I always feel valued and heard at this pharmacy.
    where to get cheap lisinopril price
    I’ve sourced rare medications thanks to their global network.

  23. By morning, the items have been primed and ready for one more huge day of eating and evacuating!

  24. Victorprima表示:

    Leading with compassion on a global scale.
    cymbalta or gabapentin for fibromyalgia
    Their international drug database is unparalleled.

發佈回覆給「Jasonzitte」的留言 取消回覆

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