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

  1. kaizenaire AI表示:

    Music began playing anytime I opened up this site, so irritating!

  2. Тут можно преобрести оружейный сейф для ружья купить оружейный сейф цена

  3. kaizenaire AI表示:

    I think this is among the most vital information for me. And i’m glad reading your article. But want to remark on few general things, The web site style is great, the articles is really great : D. Good job, cheers

  4. Hi there! Do you use Twitter? I’d like to follow you if that would be okay. I’m definitely enjoying your blog and look forward to new updates.

  5. kaizenaire AI表示:

    Thanks for another wonderful article. Where else could anyone get that type of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information.

  6. kaizenaire表示:

    I simply could not leave your site prior to suggesting that I extremely loved the standard info an individual provide on your guests? Is gonna be again continuously to investigate cross-check new posts

  7. LarryEvini表示:

    mexican drugstore online: Mexican Pharm Gate – buying from online mexican pharmacy

  8. kaizenaire表示:

    I have noticed that online degree is getting preferred because getting your degree online has turned into a popular selection for many people. A lot of people have not necessarily had a chance to attend an established college or university nevertheless seek the increased earning potential and career advancement that a Bachelor Degree grants. Still others might have a qualification in one field but would wish to pursue some thing they now develop an interest in.

  9. You can definitely see your skills in the work you write. The world hopes for even more passionate writers like you who aren’t afraid to say how they believe. Always follow your heart.

  10. Сервисный центр предлагает ремонт canon digital ixus 200 is цены ремонт canon digital ixus 200 is

  11. kaizenaire表示:

    Howdy very nice blog!! Man .. Excellent .. Wonderful .. I will bookmark your website and take the feeds also?I’m happy to find a lot of helpful info right here within the submit, we want work out more strategies on this regard, thanks for sharing. . . . . .

  12. Great items from you, man. I have take into accout your stuff prior to and you are simply extremely excellent. I actually like what you have received here, certainly like what you’re stating and the way in which you say it. You’re making it enjoyable and you still care for to keep it wise. I cant wait to learn far more from you. That is really a wonderful site.

  13. This is hands down one of the finest articles I’ve read on this topic! The author’s extensive knowledge and passion for the subject are apparent in every paragraph. I’m so appreciative for coming across this piece as it has enriched my comprehension and ignited my curiosity even further. Thank you, author, for dedicating the time to produce such a phenomenal article!

  14. Things i have constantly told men and women is that when evaluating a good online electronics retail store, there are a few components that you have to remember to consider. First and foremost, you need to make sure to choose a reputable and also reliable retailer that has gotten great testimonials and classification from other buyers and business sector people. This will make certain you are handling a well-known store providing you with good support and help to their patrons. Thank you for sharing your ideas on this blog site.

  15. GlennSnofs表示:

    mexican online pharmacies prescription drugs mexicanpharmgate.com purple pharmacy mexico price list

  16. kaizenaire AI表示:

    Thanks for another excellent article. Where else could anyone get that kind of information in such a perfect way of writing? I’ve a presentation next week, and I’m on the look for such information.

  17. Yesterday, while I was at work, my cousin stole my apple ipad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is totally off topic but I had to share it with someone!

  18. kaizenaire AI表示:

    This is undoubtedly one of the finest articles I’ve read on this topic! The author’s comprehensive knowledge and enthusiasm for the subject are evident in every paragraph. I’m so appreciative for coming across this piece as it has deepened my comprehension and stimulated my curiosity even further. Thank you, author, for dedicating the time to create such a outstanding article!

  19. Jamiecaw表示:

    https://indianpharmacyeasy.com/# india online pharmacy

  20. JefferyTar表示:

    ed and diabetes: Best Canadian online pharmacy – erection pills online

  21. Thanks for the ideas you have shared here. Yet another thing I would like to mention is that computer memory requirements generally increase along with other breakthroughs in the know-how. For instance, whenever new generations of cpus are made in the market, there’s usually a corresponding increase in the size and style preferences of both the laptop memory and hard drive room. This is because the program operated simply by these processor chips will inevitably increase in power to use the new technological know-how.

  22. Bradleygoath表示:

    https://indianpharmacyeasy.com/# buy prescription drugs from india

  23. Howdy would you mind letting me know which web host you’re working with? I’ve loaded your blog in 3 completely different web browsers and I must say this blog loads a lot faster then most. Can you recommend a good hosting provider at a honest price? Kudos, I appreciate it!

  24. Hey, you used to write wonderful, but the last several posts have been kinda boring? I miss your super writings. Past few posts are just a little out of track! come on!

發佈留言

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