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

  1. 座興とは表示:

    All business agencies are facing the same strict market and this in turn affects the other stakeholders associated with them.

  2. With havin so much written content do you ever run into any issues of plagorism or copyright infringement? My website has a lot of exclusive content I’ve either written myself or outsourced but it appears a lot of it is popping it up all over the internet without my agreement. Do you know any techniques to help stop content from being ripped off? I’d definitely appreciate it.

  3. Another thing I’ve really noticed is always that for many people, poor credit is the reaction of circumstances above their control. For instance they may happen to be saddled through an illness so they have high bills going to collections. Maybe it’s due to a employment loss or perhaps the inability to work. Sometimes divorce can send the money in the undesired direction. Thanks for sharing your thinking on this weblog.

  4. It was also concerned with development finance.

  5. One other issue is when you are in a circumstance where you will not have a co-signer then you may really want to try to exhaust all of your financial aid options. You will find many funds and other grants that will ensure that you get funds to assist with school expenses. Thanks a lot for the post.

  6. I am really inspired with your writing talents as well as with the format in your weblog. Is this a paid theme or did you modify it yourself? Anyway keep up the nice quality writing, it is uncommon to peer a great blog like this one nowadays..

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

  8. season 4表示:

    When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three emails with the same comment. Is there any way you can remove people from that service? Appreciate it!

  9. my star 2021表示:

    Great post made here. One thing I would like to say is that often most professional domains consider the Bachelors Degree as the entry level requirement for an online education. When Associate Certifications are a great way to begin, completing ones Bachelors opens many entrances to various jobs, there are numerous online Bachelor Diploma Programs available through institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another issue is that many brick and mortar institutions make available Online types of their diplomas but typically for a substantially higher amount of money than the institutions that specialize in online higher education degree plans.

  10. Audio began playing any time I opened up this website, so irritating!

  11. I really like your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to construct my own blog and would like to find out where u got this from. kudos

  12. Thanks for your fascinating article. One other problem is that mesothelioma is generally attributable to the inhalation of fibres from asbestos fiber, which is a cancer causing material. It can be commonly found among personnel in the structure industry that have long experience of asbestos. It could be caused by living in asbestos covered buildings for long periods of time, Genetic makeup plays a crucial role, and some individuals are more vulnerable on the risk when compared with others.

  13. I believe that avoiding ready-made foods is the first step in order to lose weight. They might taste beneficial, but highly processed foods contain very little nutritional value, making you take more just to have enough vitality to get throughout the day. If you’re constantly having these foods, converting to whole grains and other complex carbohydrates will help you have more energy while consuming less. Thanks alot : ) for your blog post.

  14. Thanks a bunch for sharing this with all folks you actually understand what you’re talking about! Bookmarked. Kindly also visit my website =). We could have a hyperlink trade agreement among us!

  15. Hey there! I’ve been following your website for some time now and finally got the courage to go ahead and give you a shout out from Kingwood Texas! Just wanted to mention keep up the fantastic work!

  16. See the Instructions for Form 3903 for more information.

  17. Hey just wanted to give you a brief heads up and let you know a few of the images 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 outcome.

  18. Pretty great post. I simply stumbled upon your blog and wished to say that I have really enjoyed surfing around your weblog posts. In any case I?ll be subscribing to your feed and I am hoping you write once more very soon!

  19. Useful information. Lucky me I found your site accidentally, and I’m stunned why this twist of fate didn’t came about earlier! I bookmarked it.

  20. whoah this blog is excellent i love reading your posts. Stay up the great paintings! You already know, lots of individuals are looking around for this information, you could aid them greatly.

  21. There is lot of mutual fund companies in the United States.

  22. Thanks for the tips you talk about through this site. In addition, a lot of young women who seem to become pregnant don’t even make an effort to get medical care insurance because they are full of fearfulness they probably would not qualify. Although many states right now require that insurers supply coverage despite the pre-existing conditions. Premiums on these kinds of guaranteed plans are usually greater, but when taking into consideration the high cost of health care bills it may be the safer approach to take to protect one’s financial potential.

  23. A formidable share, I just given this onto a colleague who was doing just a little analysis on this. And he in truth bought me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I really feel strongly about it and love studying extra on this topic. If possible, as you turn into expertise, would you mind updating your weblog with extra particulars? It’s highly helpful for me. Big thumb up for this weblog put up!

  24. In the grand scheme of things you’ll receive a B+ with regard to effort and hard work. Where exactly you misplaced us was first in all the particulars. You know, people say, the devil is in the details… And it could not be more correct in this article. Having said that, let me reveal to you just what did work. Your authoring is definitely highly engaging which is probably why I am taking an effort in order to comment. I do not make it a regular habit of doing that. 2nd, whilst I can easily notice the jumps in reasoning you make, I am not necessarily certain of how you seem to unite your ideas which inturn make the actual conclusion. For now I will yield to your position but hope in the near future you actually link your dots much better.

  25. After I initially commented I clicked the -Notify me when new feedback are added- checkbox and now each time a comment is added I get four emails with the identical comment. Is there any approach you’ll be able to take away me from that service? Thanks!

  26. I think one of your advertisings caused my internet browser to resize, you might want to put that on your blacklist.

  27. It can be grown on land not currently used for crops.

  28. I am not sure where you’re getting your info, but good topic. I needs to spend some time learning much more or understanding more. Thanks for fantastic info I was looking for this info for my mission.

發佈留言

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