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

15,422 Responses

  1. The youngsters love this.

  2. Houses in the area normally sell for around the 3million mark however few are this dimension.

  3. Each jurisdiction can have their own legal guidelines about mask necessities, so take note if you’re travelling around the country.

  4. However for those paying consideration and for these who’ve been following ’MintPress News’ extensive coverage of social media censorship, this revelation was merely another instance of the rising closeness between the deep state and the fourth estate.

  5. I don’t think that William Gale Breene was closely associated to Lt Col Anthony Gale, but there might have been some more distant connection, a minimum of within the sense that William Gale Breene could have been aware of his story.

  6. Classes and expertise permit gamers to customise their characters.

  7. FloydDwent表示:

    http://tadalafilo.bid/# farmacias online seguras en espaГ±a
    farmacias direct

  8. slot online表示:

    Hello! I just wish to give a huge thumbs up for the great information you’ve got right here on this post. I shall be coming again to your blog for extra soon.

  9. JamesMix表示:

    comprar viagra contrareembolso 48 horas: comprar viagra contrareembolso 48 horas – sildenafilo cinfa 100 mg precio farmacia

  10. slot online表示:

    I have observed that in digital camera models, unique devices help to {focus|concentrate|maintain focus|target|a**** automatically. Those kind of sensors with some surveillance cameras change in contrast, while others make use of a beam involving infra-red (IR) light, especially in low lumination. Higher spec cameras often use a mixture of both models and could have Face Priority AF where the digicam can ‘See’ the face and focus only on that. Thank you for sharing your opinions on this web site.

  11. JamesMix表示:

    farmacias online seguras en espaГ±a: Comprar Cialis sin receta – farmacia en casa online descuento

  12. slot online表示:

    I was wondering if you ever considered changing the page layout of your site? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or two pictures. Maybe you could space it out better?

  13. DennisRep表示:

    https://tadalafilo.bid/# farmacias online baratas

  14. Greetings! This is my first visit to your blog! We are a collection of volunteers and starting a new project in a community in the same niche. Your blog provided us valuable information to work on. You have done a extraordinary job!

  15. DennisRep表示:

    https://tadalafilo.bid/# farmacias online seguras en espaГ±a

  16. JamesMix表示:

    viagra online gibraltar: sildenafilo precio – sildenafilo 100mg precio espaГ±a

  17. For many who don’t take themselves too severely, swing by The Rialto for a $5 cocktail and a basket of fries.

  18. Operable windows in the clerestory also allow heat to escape from the house in the course of the cooling season.

  19. The corporate delivered a median constructive earnings surprise of 7.05 in the last 4 quarters.

  20. Stamp And Coin Shop On-line – U.S.A., Germany, China.

  21. The knives are hand made in Japan.

  22. I have observed that online education is getting common because getting your college degree online has developed into popular choice for many people. A large number of people have definitely not had a possible opportunity to attend a conventional college or university however seek the increased earning potential and career advancement that a Bachelor Degree gives you. Still other individuals might have a degree in one course but wish to pursue a thing they now have an interest in.

  23. DennisRep表示:

    https://sildenafilo.men/# viagra online rГЎpida

  24. If you’ll be on vacation or passing by means of as a digital nomad then yes, travel insurance is at all times, all the time, always a good idea.

  25. Her recording was issued as a single alongside with her rendition of “Wherever Love Takes Me”, a music from the movie Gold, which would compete with “We May By no means Love Like This Once more” for the perfect Song Oscar, serving as B-aspect.

  26. However I am certain that there are features of that transition that work whichever way one travels.

  27. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники в волгограде

  28. Dengan Mega888, anda boleh menikmati permainan slot dengan peluang kemenangan besar dan hadiah jackpot yang menggiurkan.

  29. You’ll want your passport to arrange your new SIM card.

發佈留言

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