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

33,709 Responses

  1. I would like to thnkx for the efforts you’ve put in writing this website. I am hoping the same high-grade web site post from you in the upcoming as well. In fact your creative writing abilities has inspired me to get my own web site now. Actually the blogging is spreading its wings quickly. Your write up is a great example of it.

  2. Louislen表示:

    https://kamagrapotenzmittel.shop/# Kamagra Oral Jelly kaufen

  3. Malcolmseern表示:

    Online apotheek Nederland zonder recept Betrouwbare online apotheek zonder recept Online apotheek Nederland met recept

  4. Michaeltor表示:

    Apotheek online bestellen: de online drogist kortingscode – Online apotheek Nederland met recept

  5. Louislen表示:

    http://apotheekmax.com/# online apotheek

  6. trc20 scan表示:

    An attention-grabbing dialogue is worth comment. I believe that you need to write more on this topic, it won’t be a taboo subject however generally persons are not enough to talk on such topics. To the next. Cheers

  7. Michaeltor表示:

    Kamagra Oral Jelly: Kamagra Gel – Kamagra kaufen ohne Rezept

  8. Malcolmseern表示:

    apotek pa nett apotek pa nett apotek online recept

  9. Thank you for your post.Really looking forward to read more. Cool.

  10. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:ремонт бытовой техники в мск
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  11. China has much much less coastline than the other three largest nations, and because nations embody a few of the continental shelf extending into the sea as their territory, China is technically fourth-largest in the world; if, on the other hand, we had been measuring solely the above-water space of every country, China would really be second largest, followed by the United States, after which Canada.

  12. Louislen表示:

    http://kamagrapotenzmittel.com/# Kamagra Oral Jelly kaufen

  13. Derekgroum表示:

    ApotheekMax: online apotheek – Apotheek Max

  14. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:ремонт бытовой техники в мск
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  15. Derekgroum表示:

    Kamagra Gel: Kamagra Gel – Kamagra kaufen ohne Rezept

  16. HomerFaw表示:

    http://kamagrapotenzmittel.com/# Kamagra online bestellen

  17. Michaeltor表示:

    Kamagra kaufen ohne Rezept: Kamagra kaufen – Kamagra kaufen

  18. Malcolmseern表示:

    Kamagra kaufen Kamagra Oral Jelly kaufen Kamagra kaufen

  19. Hey I am so thrilled I found your blog page, I really found you by error, while I was researching on Aol for something else, Anyways I am here now and would just like to say cheers for a incredible post and a all round enjoyable blog (I also love the theme/design), I don’t have time to go through it all at the minute but I have bookmarked it and also included your RSS feeds, so when I have time I will be back to read much more, Please do keep up the awesome job.

  20. To pull off your dream wedding, you need a planner who shares your vision.

  21. Derekgroum表示:

    apotek pa nett: apotek online recept – apotek pa nett

  22. Hi my friend! I wish to say that this article is amazing, nice written and include almost all significant infos. I would like to see more posts like this.

  23. Michaeltor表示:

    de online drogist kortingscode: Apotheek online bestellen – online apotheek

  24. HomerFaw表示:

    https://apotheekmax.com/# online apotheek

  25. Thanks for this excellent article. One other thing is that almost all digital cameras come equipped with a new zoom lens so that more or less of a scene for being included by simply ‘zooming’ in and out. These changes in {focus|focusing|concentration|target|the a**** length are generally reflected inside viewfinder and on huge display screen on the back of this camera.

  26. Michaeltor表示:

    Apotek hemleverans recept: apotek pa nett – Apotek hemleverans idag

  27. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:ремонт бытовой техники в мск
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

發佈留言

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