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

16,567 Responses

  1. The Profit Cap might not be applied to your Universal Credit funds for 9 months after you stopped incomes.

  2. The blushing bride wore an ivory Chantilly lace gown designed by Carmen Marc Valvo closely embellished with beading and embroidery, which she had picked out only every week earlier than the date.

  3. I have carried out this only to find that the light was defective.

  4. I can’t express how much I value the effort the author has put into writing this exceptional piece of content. The clarity of the writing, the depth of analysis, and the wealth of information presented are simply remarkable. Her zeal for the subject is evident, and it has certainly struck a chord with me. Thank you, author, for providing your knowledge and enlightening our lives with this exceptional article!

  5. A proposed quarry in Kent might destroy even more historical woodland websites than HS2 and Lower Thames Crossing combined, says the Woodland Trust.

  6. This is really attention-grabbing, You are an excessively skilled blogger. I’ve joined your rss feed and look forward to searching for extra of your excellent post. Additionally, I have shared your website in my social networks!

  7. Danieljek表示:

    buy amoxicillin online mexico https://clomidrexpharm.com/# where to buy clomid online

  8. It’s enjoyable for infants and toddlers to drop or throw food on the floor.

  9. Узнай все о на что влияет варикоцеле варикоцеле причины

  10. Larbert Establishment Studies 1892-1901.

  11. 8386 配当表示:

    2. When are you moving?

  12. 名残 とは表示:

    Shaker-impressed, deceptively easy wood cabinets carry the graceful scheme along, but their sinuous design curves like a meandering stream across the room.

  13. crypto news表示:

    Your site does not render appropriately on my blackberry – you may wanna try and fix that

  14. Bradleygoath表示:

    purchase amoxicillin 500 mg Amoxicillin buy online amoxicillin 500mg no prescription

  15. StevenNub表示:

    prednisone without rx: cheap prednisone – 1 mg prednisone cost

  16. Women who studied law, economics or medication earned over £250,000 more throughout their profession than if they had not acquired a level.

  17. For those who already get an element for managed migration or an SDP, your Universal Credit score cost may not go up by the whole amount of the LCWRA component.

  18. We purchased her an illustrated dinosaur e book that explains loss of life to youngsters in a secular way.

  19. The song had been used to mark the exit of contestants as they had been voted off the present.

  20. On June 21, 2011, the hospital introduced that its name was altering from The Youngsters’s Hospital to Children’s Hospital Colorado.

  21. Only downside? Neither of you should have the satisfying joy of saying “checkmate” out loud on your opponent to listen to.

  22. Sazrexg表示:

    Официальная покупка диплома вуза с сокращенной программой обучения в Москве
    simple-com.ru/forum/user/2080/

  23. Lilian Bernice Lynch, British topic resident in France.

  24. 眺 書き順表示:

    In addition, the two named councils, and more, accumulate meals waste together with garden waste, by sending out kitchen caddies and compostable bin liners.

  25. The collection is ready in Memphis, Tennessee and follows Elijiah Straight (Smits) and his daughter Sydney (McGee), each of whom work at a law agency that specializes in dealing with civil rights instances, lots of that are thought of controversial.

  26. MH and VHO reserving the traditional fluorescents for “least demanding animals in shallow aquaria 40 cm or much less in depth”.

  27. Hi! This is my first visit to your blog! We are a group of volunteers and starting a new project in a community in the same niche. Your blog provided us useful information to work on. You have done a outstanding job!

  28. 界面新闻.新浪新闻.

發佈留言

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