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

  1. Charlesrab表示:

    pharmacie en ligne france fiable cialis prix pharmacie en ligne fiable

  2. mzplay表示:

    Hey there just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same results.

  3. mzplay表示:

    F*ckin? amazing things here. I?m very glad to see your post. Thanks a lot and i’m looking forward to contact you. Will you kindly drop me a mail?

  4. JamesEMULK表示:

    Решение судопроизводства по гражданским и уголовным делам, органов военной прокуратуры часто принимается на основании выводов судебной пожарно-технической экспертизы.

    Моя экспертная помощь поможет вам определить места возникновения первоначального горения (очага, направления распространения горения, особенностей), механизма возникновения и развития горения, а также выявить обстоятельства возгорания, чтобы суд смог вынести правильное решение по делу: в получении компенсации за причиненный вам вред, в доказательстве непричастности к возгоранию и пр.

  5. mzplay表示:

    Hi my friend! I want to say that this article is awesome, nice written and include almost all important infos. I would like to see more posts like this.

  6. mzplay表示:

    whoah this blog is great i like reading your posts. Keep up the good work! You recognize, a lot of persons are hunting round for this information, you could aid them greatly.

  7. Louisbealo表示:

    Судебная пожарно-техническая экспертизаСудебная пожарно-техническая экспертиза для установления причин возгорания пожара промышленных объектов, жилых домов, квартир, автомобильного транспорта (легкового и грузового) и т.д.
    Судебное экспертное электротехническое исследованиеСудебное экспертное исследование систем электроснабжения на исследуемых объектах на соответствие требованиям монтажа и эксплуатации согласно с Правилам устройства электроустановок в Республике Казахстан.
    Судебное экспертиза обстоятельств пожараСудебное экспертное исследование объектов для установления механизма и причин возникновения пожара.
    Судебное экспертиза веществ и материаловСудебная экспертиза веществ и материалов на предмет определения горючести материалов и веществ и возможности их воспламенения и самовозгорания.
    Судебное экспертное исследование нефтепродуктов и горюче-смазочных материаловСудебно – экспертное исследование нефтепродуктов и горюче-смазочных материалов на предмет их наличия на месте возникновения пожара.

  8. mzplay表示:

    I have noticed that smart real estate agents everywhere you go are warming up to FSBO ***********. They are realizing that it’s more than simply placing a sign in the front area. It’s really with regards to building associations with these retailers who at some time will become consumers. So, after you give your time and energy to aiding these traders go it alone — the “Law regarding Reciprocity” kicks in. Thanks for your blog post.

  9. mzplay表示:

    This article is absolutely incredible! The author has done a phenomenal job of delivering the information in an compelling and educational manner. I can’t thank him enough for sharing such valuable insights that have certainly enhanced my awareness in this topic. Bravo to her for crafting such a gem!

  10. mzplay表示:

    Hi there, I discovered your web site by means of Google at the same time as looking for a related topic, your web site came up, it appears to be like great. I’ve bookmarked it in my google bookmarks.

  11. mzplay表示:

    Fantastic web site. Lots of useful information here. I am sending it to a few friends ans also sharing in delicious. And naturally, thanks for your sweat!

  12. mzplay表示:

    Nice post. I study something more difficult on different blogs everyday. It’ll at all times be stimulating to read content material from other writers and apply a bit something from their store. I?d choose to use some with the content material on my weblog whether you don?t mind. Natually I?ll provide you with a link in your net blog. Thanks for sharing.

  13. mzplay表示:

    Hello there! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

  14. Charlesrab表示:

    pharmacie en ligne france fiable pharmacie en ligne pas cher Pharmacie sans ordonnance

  15. mzplay表示:

    Thanks for the something totally new you have revealed in your text. One thing I’d like to comment on is that FSBO connections are built after some time. By introducing yourself to owners the first weekend break their FSBO will be announced, prior to a masses commence calling on Friday, you build a good link. By mailing them tools, educational components, free reports, and forms, you become a good ally. Through a personal affinity for them along with their situation, you develop a solid link that, in many cases, pays off once the owners decide to go with a broker they know as well as trust – preferably you actually.

  16. mzplay表示:

    I’m not sure why but this web site is loading extremely slow for me. Is anyone else having this problem or is it a issue on my end? I’ll check back later and see if the problem still exists.

  17. Stephengen表示:

    http://clssansordonnance.icu/# pharmacie en ligne livraison europe

  18. mzplay表示:

    Youre so cool! I dont suppose Ive learn something like this before. So nice to search out any person with some unique thoughts on this subject. realy thank you for starting this up. this website is one thing that is needed on the internet, someone with somewhat originality. helpful job for bringing one thing new to the web!

  19. Amcyxs表示:

    cheap prednisone 10mg – prednisolone online buy cheap elimite

  20. HeathZex表示:

    pharmacie en ligne: pharmacie en ligne – pharmacie en ligne fiable

  21. mzplay表示:

    Hello! I know this is kinda off topic but I was wondering which blog platform are you using for this website? I’m getting sick and tired of WordPress because I’ve had problems with hackers and I’m looking at options for another platform. I would be awesome if you could point me in the direction of a good platform.

  22. HeathZex表示:

    pharmacie en ligne france fiable: cialis sans ordonnance – Pharmacie sans ordonnance

  23. mzplay表示:

    I’m often to running a blog and i actually respect your content. The article has actually peaks my interest. I am going to bookmark your site and maintain checking for brand new information.

  24. mzplay表示:

    Via my observation, shopping for electronics online can for sure be expensive, but there are some how-to’s that you can use to acquire the best discounts. There are constantly ways to discover discount specials that could make one to hold the best electronic devices products at the lowest prices. Great blog post.

  25. HeathZex表示:

    Prix du Viagra 100mg en France: Viagra sans ordonnance 24h – Viagra homme prix en pharmacie sans ordonnance

  26. mzplay表示:

    Hi there, You have done an excellent job. I will certainly digg it and personally suggest to my friends. I am sure they will be benefited from this site.

  27. mzplay表示:

    Hey there! Would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would really enjoy your content. Please let me know. Many thanks

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

  29. mzplay表示:

    I like what you guys are usually up too. This type of clever work and exposure! Keep up the wonderful works guys I’ve incorporated you guys to my personal blogroll.

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

發佈留言

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