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

  1. Howdy! This is kind of off topic but I need some advice from an established blog. Is it very difficult to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about setting up my own but I’m not sure where to start. Do you have any tips or suggestions? With thanks

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

  3. I’ve come across that these days, more and more people are attracted to camcorders and the industry of digital photography. However, being a photographer, it’s important to first invest so much period deciding the exact model of dslr camera to buy in addition to moving out of store to store just so you could potentially buy the most economical camera of the trademark you have decided to pick. But it isn’t going to end at this time there. You also have to think about whether you should purchase a digital video camera extended warranty. Thanks a lot for the good guidelines I received from your weblog.

  4. Generally I don’t learn article on blogs, however I wish to say that this write-up very pressured me to take a look at and do it! Your writing taste has been amazed me. Thank you, quite great post.

  5. Greetings from Los angeles! I’m bored at work so I decided to browse your website on my iphone during lunch break. I enjoy the information you present here and can’t wait to take a look when I get home. I’m shocked at how quick your blog loaded on my mobile .. I’m not even using WIFI, just 3G .. Anyways, good blog!

  6. I do not even know how I ended up here, but I thought this post was good. I don’t know who you are but definitely you’re going to a famous blogger if you aren’t already 😉 Cheers!

  7. I know this if off topic but I’m looking into starting my own blog and was wondering what all is required to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet smart so I’m not 100 positive. Any recommendations or advice would be greatly appreciated. Kudos

  8. It?s actually a great and useful piece of info. I am glad that you shared this helpful info with us. Please keep us up to date like this. Thanks for sharing.

  9. I haven?t checked in here for a while since I thought it was getting boring, but the last few posts are good quality so I guess I will add you back to my daily bloglist. You deserve it my friend 🙂

  10. I am grateful for your post. I’d really like to write my opinion that the price of car insurance differs from one policy to another, since there are so many different facets which play a role in the overall cost. Such as, the model and make of the car will have a significant bearing on the price. A reliable old family automobile will have a more affordable premium than the usual flashy expensive car.

  11. Thanks for your posting on this website. From my very own experience, there are occassions when softening right up a photograph could provide the digital photographer with a little bit of an artsy flare. Many times however, that soft clouds isn’t what exactly you had under consideration and can usually spoil an otherwise good photo, especially if you thinking about enlarging them.

  12. Does your website have a contact page? I’m having problems locating it but, I’d like to shoot you an e-mail. I’ve got some creative ideas for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it grow over time.

  13. whippet news表示:

    Do you have a spam problem on this site; I also am a blogger, and I was wanting to know your situation; many of us have created some nice procedures and we are looking to swap techniques with other folks, be sure to shoot me an email if interested.

  14. twerk comp表示:

    Thanks a lot for sharing this with all of us you actually know what you’re talking about! Bookmarked. Kindly also visit my website =). We could have a link exchange contract between us!

  15. Hi, Neat post. There’s a problem with your site in internet explorer, would check this? IE still is the market leader and a large portion of people will miss your wonderful writing due to this problem.

  16. I have observed that of all forms of insurance, health insurance is the most controversial because of the turmoil between the insurance cover company’s necessity to remain making money and the customer’s need to have insurance cover. Insurance companies’ earnings on overall health plans have become low, consequently some companies struggle to profit. Thanks for the thoughts you talk about through this web site.

  17. Heya i?m for the first time here. I came across this board and I to find It truly helpful & it helped me out much. I am hoping to present something back and aid others such as you aided me.

  18. I have come to understand that rates for internet degree specialists tend to be an excellent value. Like a full Bachelor’s Degree in Communication from The University of Phoenix Online consists of 60 credits at $515/credit or $30,900. Also American Intercontinental University Online comes with a Bachelors of Business Administration with a whole course element of 180 units and a worth of $30,560. Online degree learning has made obtaining your higher education degree much simpler because you can certainly earn your current degree in the comfort of your home and when you finish from work. Thanks for all tips I have really learned from your web site.

  19. Howdy! Someone in my Myspace group shared this website with us so I came to check it out. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers! Fantastic blog and outstanding design.

  20. twerk tube表示:

    Heya i?m for the primary time here. I came across this board and I in finding It really helpful & it helped me out a lot. I’m hoping to offer one thing back and aid others like you aided me.

  21. dance twerk表示:

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

  22. I’ve been absent for a while, but now I remember why I used to love this web site. Thanks , I?ll try and check back more frequently. How frequently you update your website?

  23. I’m extremely impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you modify it yourself? Anyway keep up the excellent quality writing, it?s rare to see a great blog like this one these days..

  24. I have observed that charges for internet degree specialists tend to be a great value. For instance a full Bachelors Degree in Communication from The University of Phoenix Online consists of Sixty credits with $515/credit or $30,900. Also American Intercontinental University Online makes available Bachelors of Business Administration with a entire program feature of 180 units and a worth of $30,560. Online degree learning has made getting the college degree been so cool because you may earn your degree through the comfort of your dwelling place and when you finish from office. Thanks for other tips I have learned through your website.

  25. StephenDeery表示:

    Ежегодно в течение сентября проходит Тюменский инновационный форум «НЕФТЬГАЗТЭК».
    Форум посвящен развитию способов инновационного продвижения отраслей топливно-энергетического комплекса, рассмотрению и поиску ответов, организации благоприятных условий для расчета инноваторских проектов. Ежегодный тюменский форум представляетсобой важной дискуссионной площадкой по продвижению нефтегазовой отрасли в России, содержит большой статус и своевременность, созвучен корпоративной стратегии продвижения инновационного направления в Российской Федерации
    -https://neftgaztek.ru/

  26. DichaelDax表示:

    Ежегодно в течение сентября организовывается Тюменский инновационный форум «НЕФТЬГАЗТЭК».
    Форум посвящен развитию механизмов инноваторского развития отраслей топливно-энергетического комплекса, обсуждению а также изысканию заключений, созданию наилучших обстоятельств для развития инноваторских проектов. Ежегодный тюменский форум является важной дискуссионной площадкой по развитию нефтегазовой сферы в России, имеет высокий авторитет и актуальность, созвучен корпоративной стратегии формирования инноваторского направления в Российской Федерации
    -https://neftgaztek.ru/

  27. Kmribc表示:

    feldene 20mg cheap – feldene 20 mg us order exelon 6mg

  28. Отличный сайт! Всем рекомендую!Тут Вы можете приобрестизакись азота купить

  29. Отличный сайт! Всем рекомендую!Тут Вы можете приобрестивеселящий газ

發佈留言

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