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

10,890 Responses

  1. Casa de apostas com as melhores avaliacoes Tigrinho

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

  3. Recomendo o melhor cassino Tigrinho

  4. Your home is valueble for me. Thanks!?

  5. As I site possessor I believe the content matter here is rattling wonderful , appreciate it for your hard work. You should keep it up forever! Good Luck.

  6. I know this if off topic but I’m looking into starting my own blog and was curious what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web smart so I’m not 100 sure. Any recommendations or advice would be greatly appreciated. Appreciate it

  7. One thing I’d really like to say is that before buying more computer memory, look into the machine in to which it is installed. Should the machine will be running Windows XP, for instance, the memory limit is 3.25GB. Installing a lot more than this would merely constitute just a waste. Make sure that one’s motherboard can handle your upgrade quantity, as well. Great blog post.

  8. You really make it seem so easy with your presentation but I find this topic to be really something that I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!

  9. Some tips i have constantly told people is that when looking for a good online electronics retail store, there are a few factors that you have to factor in. First and foremost, you need to make sure to choose a reputable and reliable retailer that has enjoyed great opinions and rankings from other buyers and business sector professionals. This will make sure that you are getting along with a well-known store that can offer good assistance and support to their patrons. Thanks for sharing your ideas on this web site.

  10. explore more表示:

    This is undoubtedly one of the finest articles I’ve read on this topic! The author’s extensive knowledge and enthusiasm for the subject shine through in every paragraph. I’m so appreciative for stumbling upon this piece as it has enriched my comprehension and sparked my curiosity even further. Thank you, author, for dedicating the time to produce such a outstanding article!

  11. monsterdildo表示:

    I think other web site proprietors should take this website as an model, very clean and fantastic user friendly style and design, let alone the content. You are an expert in this topic!

  12. Cassinos com as melhores avaliacoes Tigrinho

  13. Another issue is that video games are generally serious anyway with the most important focus on finding out rather than amusement. Although, it comes with an entertainment part to keep your kids engaged, every game is normally designed to work with a specific set of skills or area, such as mathematics or scientific disciplines. Thanks for your publication.

  14. Tente a sua sorte neste cassino Tigrinho

  15. Generally I don’t read article on blogs, but I would like to say that this write-up very forced me to try and do so! Your writing style has been amazed me. Thanks, very nice article.

  16. click here表示:

    Many thanks for this article. I would also like to convey that it can be hard when you’re in school and merely starting out to create a long credit history. There are many learners who are only trying to pull through and have a long or favourable credit history can often be a difficult point to have.

  17. explore more表示:

    My programmer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using Movable-type on a variety of websites for about a year and am worried about switching to another platform. I have heard excellent things about blogengine.net. Is there a way I can transfer all my wordpress posts into it? Any kind of help would be really appreciated!

  18. click here表示:

    I relish, result in I found just what I was taking a look for. You’ve ended my 4 day long hunt! God Bless you man. Have a great day. Bye

  19. Thank you for sharing superb informations. Your website is very cool. I’m impressed by the details that you?ve on this website. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found just the info I already searched everywhere and just could not come across. What a great website.

  20. Allenacurf表示:

    trouver un mГ©dicament en pharmacie: cialis sans ordonnance – vente de mГ©dicament en ligne

  21. click here表示:

    The crux of your writing while sounding reasonable in the beginning, did not work properly with me after some time. Somewhere within the sentences you actually managed to make me a believer but just for a very short while. I still have got a problem with your jumps in logic and you might do well to fill in all those breaks. If you can accomplish that, I would surely be impressed.

  22. click here表示:

    Unquestionably believe that which you said. Your favorite reason seemed to be on the internet the simplest thing to be aware of. I say to you, I certainly get irked while people consider worries that they plainly don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people can take a signal. Will probably be back to get more. Thanks

  23. Robertdiz表示:

    pharmacie en ligne sans ordonnance: kamagra pas cher – Achat mГ©dicament en ligne fiable

  24. JuliusIntal表示:

    Prix du Viagra 100mg en France: Viagra generique en pharmacie – Viagra gГ©nГ©rique pas cher livraison rapide

  25. Seo_pqoi表示:

    продвижение сайтов частник http://prodvizhenie-sajtov-v-moskve111.ru/ .

  26. Confie neste cassino confiavel Tigrinho

  27. shop now表示:

    One more thing. It’s my opinion that there are numerous travel insurance web-sites of reputable companies that allow you enter your vacation details and find you the quotations. You can also purchase this international holiday insurance policy on the net by using the credit card. All you have to do is to enter your own travel details and you can see the plans side-by-side. Simply find the system that suits your finances and needs then use your credit card to buy that. Travel insurance on the web is a good way to search for a dependable company with regard to international travel insurance. Thanks for expressing your ideas.

  28. Allenacurf表示:

    Viagra gГ©nГ©rique sans ordonnance en pharmacie: Meilleur Viagra sans ordonnance 24h – Viagra homme sans prescription

  29. Hello there, just became alert to your blog through Google, and found that it is truly informative. I?m gonna watch out for brussels. I?ll appreciate if you continue this in future. Numerous people will be benefited from your writing. Cheers!

  30. click here表示:

    I love what you guys tend to be up too. Such clever work and reporting! Keep up the fantastic works guys I’ve added you guys to blogroll.

發佈留言

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