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

11,382 Responses

  1. Thanks for the ideas you have contributed here. Another thing I would like to mention is that laptop or computer memory requirements generally go up along with other developments in the technology. For instance, if new generations of processor chips are brought to the market, there’s usually a similar increase in the scale demands of both laptop or computer memory along with hard drive room. This is because the application operated simply by these cpus will inevitably boost in power to benefit from the new technological know-how.

  2. Thank you, I’ve recently been seeking for info about this topic for ages and yours is the best I’ve located so far.

  3. With havin so much content do you ever run into any problems of plagorism or copyright infringement? My site has a lot of completely unique content I’ve either created myself or outsourced but it looks like a lot of it is popping it up all over the internet without my authorization. Do you know any methods to help reduce content from being stolen? I’d genuinely appreciate it.

  4. Wow! This can be one particular of the most beneficial blogs We have ever arrive across on this subject. Basically Great. I am also a specialist in this topic so I can understand your effort.

  5. Heya! I’m at work surfing around your blog from my new iphone 4! Just wanted to say I love reading your blog and look forward to all your posts! Carry on the excellent work!

  6. you are actually a excellent webmaster. The site loading speed is amazing. It sort of feels that you’re doing any unique trick. Also, The contents are masterpiece. you’ve performed a excellent activity in this matter!

  7. Interesting blog post. What I would like to bring up is that computer system memory ought to be purchased if the computer still can’t cope with anything you do along with it. One can put in two RAM boards having 1GB each, in particular, but not one of 1GB and one having 2GB. One should always check the car maker’s documentation for own PC to be certain what type of ram it can take.

  8. I have seen that nowadays, more and more people are being attracted to surveillance cameras and the field of pictures. However, really being a photographer, you will need to first expend so much period deciding the model of digital camera to buy and also moving store to store just so you may buy the lowest priced camera of the brand you have decided to pick out. But it would not end there. You also have to consider whether you can purchase a digital camera extended warranty. Thx for the good points I acquired from your weblog.

  9. Thanks for your tips about this blog. One particular thing I wish to say is the fact purchasing gadgets items through the Internet is nothing new. In reality, in the past few years alone, the marketplace for online gadgets has grown significantly. Today, you will discover practically any kind of electronic unit and other gadgets on the Internet, which include cameras in addition to camcorders to computer elements and games consoles.

  10. Thanks a lot for your post. I would like to comment that the expense of car insurance varies from one policy to another, given that there are so many different issues which bring about the overall cost. One example is, the make and model of the automobile will have a significant bearing on the purchase price. A reliable older family auto will have a more affordable premium than the usual flashy racecar.

  11. Отличный сайт! Всем рекомендую!рейтинг сайтов

  12. Hi there! Someone in my Facebook group shared this website with us so I came to take a look. I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers! Wonderful blog and superb design.

  13. Good day I am so delighted I found your blog page, I really found you by mistake, while I was looking on Aol for something else, Anyhow I am here now and would just like to say kudos for a tremendous post and a all round interesting blog (I also love the theme/design), I don’t have time to go through it all at the minute but I have bookmarked it and also added in your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the excellent work.

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

  15. I?ll right away grab your rss as I can’t find your e-mail subscription link or e-newsletter service. Do you have any? Please let me know so that I could subscribe. Thanks.

  16. I have taken notice that in old digital cameras, unique receptors help to {focus|concentrate|maintain focus|target|a**** automatically. The particular sensors connected with some surveillance cameras change in contrast, while others use a beam with infra-red (IR) light, especially in low light. Higher spec cameras from time to time use a combination of both systems and probably have Face Priority AF where the digital camera can ‘See’ a new face while keeping focused only on that. Thank you for sharing your thinking on this blog site.

  17. okmark your weblog and check again here frequently. I am quite certain I?ll learn plenty of new stuff right here! Best of luck for the next!

  18. Matthewchact表示:

    femara vs tamoxifen: tamoxifen endometriosis – where to get nolvadex

  19. Thanks for the a new challenge you have uncovered in your text. One thing I’d like to discuss is that FSBO associations are built after a while. By bringing out yourself to owners the first few days their FSBO is announced, prior to the masses start out calling on Friday, you generate a good association. By mailing them equipment, educational products, free accounts, and forms, you become a good ally. If you take a personal affinity for them as well as their circumstance, you build a solid interconnection that, most of the time, pays off if the owners decide to go with an agent they know and trust — preferably you.

  20. I think other web-site proprietors should take this website as an model, very clean and excellent user genial style and design, as well as the content. You’re an expert in this topic!

  21. An attention-grabbing discussion is worth comment. I feel that it is best to write more on this topic, it might not be a taboo topic however typically people are not enough to talk on such topics. To the next. Cheers

  22. Wow! This could be one particular of the most helpful blogs We’ve ever arrive across on this subject. Basically Fantastic. I’m also a specialist in this topic therefore I can understand your hard work.

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

  24. HighStakesDB表示:

    Feel free to visit my site :: HighStakesDB

  25. I’ve been absent for some time, but now I remember why I used to love this web site. Thank you, I will try and check back more often. How frequently you update your web site?

  26. Hmm it appears like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to everything. Do you have any tips and hints for inexperienced blog writers? I’d certainly appreciate it.

  27. Hey! This is kind of off topic but I need some help from an established blog. Is it 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? Many thanks

  28. You can certainly see your expertise in the paintings you write. The world hopes for more passionate writers like you who aren’t afraid to say how they believe. At all times follow your heart.

  29. GichardPheve表示:

    I blog quite often and I seriously thank you for your content. The article has truly peaked my interest. I am going to take a note of your website and keep checking for new details about once per week. I subscribed to your Feed too.

    https://gorod.kr.ua/forum/showthread.php?t=55714

發佈留言

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