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,252 Responses

  1. Jasonzitte表示:

    Their international team is incredibly knowledgeable.
    where buy cheap clomid without insurance
    Their health awareness campaigns are so informative.

  2. Hello there, just became alert to your blog through Google, and found that it’s truly informative. I am going to watch out for brussels. I?ll appreciate if you continue this in future. A lot of people will be benefited from your writing. Cheers!

  3. Victorprima表示:

    Their global approach ensures unparalleled care.
    can you get cheap cytotec online
    A model pharmacy in terms of service and care.

  4. Howdy! This post couldn’t be written any better! Reading this post reminds me of my good old room mate! He always kept chatting about this. I will forward this article to him. Fairly certain he will have a good read. Thanks for sharing!

  5. Jasonzitte表示:

    They provide a world of health solutions.
    gabapentin katze dosierung
    Love their spacious and well-lit premises.

  6. Victorprima表示:

    Always up-to-date with the latest healthcare trends.
    where to get generic clomid no prescription
    Their compounding services are impeccable.

  7. Jasonzitte表示:

    Long-Term Effects.
    where to buy cheap cytotec without dr prescription
    They provide peace of mind with their secure international deliveries.

  8. I?ll immediately grasp your rss feed as I can not in finding your e-mail subscription link or newsletter service. Do you’ve any? Kindly allow me realize so that I may just subscribe. Thanks.

  9. Victorprima表示:

    Global expertise that’s palpable with every service.
    lisinopril pill cost
    Always stocked with what I need.

  10. Victorprima表示:

    Providing international caliber services consistently.
    how can i get cheap cytotec tablets
    They have a great selection of wellness products.

  11. I know this if off topic but I’m looking into starting my own blog and was wondering what all is needed to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet smart so I’m not 100 sure. Any tips or advice would be greatly appreciated. Cheers

  12. I used to be very pleased to search out this net-site.I wished to thanks for your time for this glorious learn!! I undoubtedly having fun with every little little bit of it and I’ve you bookmarked to take a look at new stuff you blog post.

  13. Section 1061 will increase the holding interval required for lengthy-time period capital positive factors remedy from multiple 12 months to more than three years for partnership interests deemed to be “applicable partnership interests” (“API”).

  14. Jasonzitte表示:

    A trusted partner for patients worldwide.
    buy cipro prices
    Always ahead of the curve with global healthcare trends.

  15. Jasonzitte表示:

    A reliable pharmacy that connects patients globally.
    how to get lisinopril prices
    They ensure global standards in every pill.

  16. An additional issue is that video games are typically serious anyway with the major focus on finding out rather than entertainment. Although, it comes with an entertainment part to keep children engaged, each game is generally designed to work towards a specific expertise or area, such as math concepts or scientific research. Thanks for your write-up.

  17. Victorprima表示:

    Leading the way in global pharmaceutical services.
    gabapentin accion
    Their 24/7 support line is super helpful.

  18. Thanks for helping me to achieve new concepts about pcs. I also hold the belief that certain of the best ways to keep your laptop in perfect condition is by using a hard plastic material case, as well as shell, that matches over the top of one’s computer. A majority of these protective gear are model distinct since they are made to fit perfectly on the natural covering. You can buy them directly from the owner, or from third party sources if they are readily available for your notebook computer, however not every laptop may have a cover on the market. Again, thanks for your guidelines.

  19. For many of us who participated in athletic sports activities in high school, the competition stopped when we graduated.

  20. Several developments in wedding ceremony day photography could make your entire course of way more predictable and fewer annoying.

  21. Wonderful goods from you, man. I have understand your stuff previous to and you’re just extremely excellent. I actually like what you’ve acquired here, really like what you are stating and the way in which you say it. You make it enjoyable and you still take care of to keep it smart. I can’t wait to read far more from you. This is actually a wonderful site.

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

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