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. idx 69311500表示:

    Thanks for the suggestions you have provided here. Something important I would like to express is that laptop or computer memory specifications generally go up along with other developments in the technology. For instance, whenever new generations of processor chips are made in the market, there is certainly usually a similar increase in the size and style preferences of both personal computer memory as well as hard drive room. This is because the software operated by these cpus will inevitably boost in power to benefit from the new know-how.

  2. Peterhew表示:

    best india pharmacy: buy prescription drugs from india – best online pharmacy india

  3. I have taken notice that in digital camera models, exceptional detectors help to {focus|concentrate|maintain focus|target|a**** automatically. The sensors with some video cameras change in contrast, while others use a beam involving infra-red (IR) light, specially in low lumination. Higher spec cameras oftentimes use a blend of both models and probably have Face Priority AF where the dslr camera can ‘See’ the face while keeping your focus only on that. Many thanks for sharing your opinions on this blog.

  4. Even better, transactions are conducted directly from peer to peer, circumventing banks with their meddlesome rules and fees.

  5. Thank you for sharing these wonderful threads. In addition, the right travel and also medical insurance strategy can often reduce those considerations that come with travelling abroad. The medical emergency can quickly become costly and that’s certain to quickly decide to put a financial impediment on the family’s finances. Putting in place the ideal travel insurance offer prior to leaving is worth the time and effort. Thanks

  6. I just like the valuable info you provide for your articles. I?ll bookmark your blog and take a look at once more right here regularly. I am reasonably sure I?ll learn many new stuff proper right here! Best of luck for the next!

  7. I have figured out some considerations through your website post. One other subject I would like to mention is that there are various games available and which are designed in particular for toddler age children. They include things like pattern identification, colors, animals, and designs. These commonly focus on familiarization as opposed to memorization. This will keep a child occupied without having a sensation like they are studying. Thanks

  8. ฮายxx表示:

    Usually I don’t read article on blogs, but I wish to say that this write-up very forced me to check out and do so! Your writing style has been surprised me. Thank you, quite nice post.

  9. My developer is trying to persuade 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 several websites for about a year and am anxious 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!

  10. Robertengep表示:

    https://easyrxindia.com/# pharmacy website india

  11. One other issue is that if you are in a situation where you do not possess a cosigner then you may want to try to exhaust all of your money for college options. You will discover many grants and other free college funding that will supply you with funding to aid with classes expenses. Thanks for the post.

  12. Hi are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and create my own. Do you need any html coding expertise to make your own blog? Any help would be greatly appreciated!

  13. This is very interesting, You’re a very skilled blogger. I have joined your rss feed and look forward to seeking more of your excellent post. Also, I’ve shared your website in my social networks!

  14. I loved as much as you’ll receive carried out right here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you shield this increase.

  15. I have really learned some new things from a blog post. One more thing to I have recognized is that usually, FSBO sellers are going to reject an individual. Remember, they can prefer to never use your expert services. But if a person maintain a comfortable, professional partnership, offering aid and keeping contact for four to five weeks, you will usually be capable to win interviews. From there, a house listing follows. Thanks a lot

  16. What?s Happening i’m new to this, I stumbled upon this I have found It positively useful and it has helped me out loads. I am hoping to contribute & assist different customers like its aided me. Great job.

  17. I was recommended this website by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my trouble. You’re amazing! Thanks!

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

  19. Excellent blog right here! Additionally your web site loads up fast! What web host are you the usage of? Can I am getting your associate link to your host? I wish my site loaded up as fast as yours lol

  20. I have noticed that in cameras, unique sensors help to {focus|concentrate|maintain focus|target|a**** automatically. The particular sensors associated with some cams change in in the area of contrast, while others make use of a beam involving infra-red (IR) light, specially in low lumination. Higher standards cameras often use a mix of both devices and likely have Face Priority AF where the digicam can ‘See’ your face while keeping focused only in that. Many thanks for sharing your opinions on this website.

  21. Hey there, You’ve done an excellent job. I will definitely digg it and personally suggest to my friends. I’m sure they’ll be benefited from this site.

  22. Hi there! I could have sworn I’ve been to this site before but after reading through some of the post I realized it’s new to me. Nonetheless, I’m definitely delighted I found it and I’ll be bookmarking and checking back often!

  23. It’s the best time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or suggestions. Perhaps you could write next articles referring to this article. I desire to read even more things about it!

  24. The other day, while I was at work, my sister stole my iphone and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is totally off topic but I had to share it with someone!

  25. Hmm is anyone else having problems with the pictures on this blog loading? I’m trying to find out if its a problem on my end or if it’s the blog. Any suggestions would be greatly appreciated.

  26. Pretty nice post. I just stumbled upon your weblog and wanted to mention that I have truly enjoyed surfing around your blog posts. After all I will be subscribing for your feed and I hope you write again soon!

  27. Hermanswoff表示:

    mexico pharmacies prescription drugs: medication from mexico pharmacy – mexican pharmacy

  28. Its such as you read my mind! You seem to know so much approximately this, like you wrote the e book in it or something. I believe that you could do with a few percent to power the message house a little bit, however instead of that, this is magnificent blog. A fantastic read. I will certainly be back.

  29. I was just looking for this info for some time. After six hours of continuous Googleing, at last I got it in your website. I wonder what’s the lack of Google strategy that don’t rank this type of informative websites in top of the list. Generally the top websites are full of garbage.

發佈留言

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