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

  1. Jogue e ganhe no melhor cassino Blaze

  2. Aventura e diversao em um so cassino Blaze

  3. Thanks for your tips on this blog. 1 thing I would like to say is the fact purchasing gadgets items from the Internet is not something new. In reality, in the past 10 years alone, the market for online electronic products has grown substantially. Today, you can find practically any specific electronic tool and tools on the Internet, from cameras in addition to camcorders to computer spare parts and video games consoles.

  4. I have discovered some new points from your website about personal computers. Another thing I’ve always assumed is that computer systems have become an item that each house must have for many reasons. They provide convenient ways to organize the home, pay bills, shop, study, listen to music and in many cases watch tv shows. An innovative method to complete these types of tasks is by using a computer. These pc’s are portable ones, small, potent and lightweight.

  5. I am so happy to read this. This is the type of manual that needs to be given and not the accidental misinformation that’s at the other blogs. Appreciate your sharing this greatest doc.

  6. I have seen many useful factors on your web site about pcs. However, I have got the thoughts and opinions that notebooks are still not nearly powerful more than enough to be a option if you often do tasks that require loads of power, just like video enhancing. But for internet surfing, word processing, and a lot other popular computer functions they are fine, provided you don’t mind the tiny screen size. Thank you sharing your thinking.

  7. Hello! Would you mind if I share your blog with my myspace group? There’s a lot of people that I think would really enjoy your content. Please let me know. Thanks

  8. Heya this is somewhat of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding know-how so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!

  9. Great blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple adjustements would really make my blog stand out. Please let me know where you got your theme. With thanks

  10. I’ve been surfing online more than three hours today, yet I never found any interesting article like yours. It?s pretty worth enough for me. In my opinion, if all web owners and bloggers made good content as you did, the internet will be much more useful than ever before.

  11. Wonderful work! This is the type of information that should be shared around the internet. Shame on Google for not positioning this post higher! Come on over and visit my site . Thanks =)

  12. Thanks for the new things you have disclosed in your writing. One thing I would like to touch upon is that FSBO human relationships are built over time. By introducing yourself to the owners the first end of the week their FSBO is actually announced, prior to masses commence calling on Friday, you create a good relationship. By sending them resources, educational resources, free accounts, and forms, you become the ally. By taking a personal affinity for them plus their circumstance, you produce a solid interconnection that, on many occasions, pays off if the owners decide to go with a representative they know along with trust – preferably you.

  13. Thanks for the concepts you talk about through this blog. In addition, lots of young women who seem to become pregnant will not even try to get health care insurance because they fear they won’t qualify. Although a lot of states right now require that insurers supply coverage irrespective of the pre-existing conditions. Premiums on these types of guaranteed programs are usually bigger, but when considering the high cost of medical treatment it may be any safer approach to take to protect the financial potential.

  14. I have observed that charges for on-line degree authorities tend to be a great value. For instance a full Bachelor’s Degree in Communication in the University of Phoenix Online consists of Sixty credits from $515/credit or $30,900. Also American Intercontinental University Online comes with a Bachelors of Business Administration with a total education course feature of 180 units and a cost of $30,560. Online studying has made taking your certification so much easier because you can earn your current degree through the comfort in your home and when you finish working. Thanks for all the other tips I have learned from your website.

  15. Thanks for expressing your ideas with this blog. As well, a myth regarding the finance institutions intentions if talking about property foreclosure is that the traditional bank will not take my repayments. There is a certain quantity of time that this bank can take payments every now and then. If you are very deep inside hole, they’re going to commonly desire that you pay that payment completely. However, i am not saying that they will have any sort of payments at all. When you and the financial institution can have the ability to work a little something out, the particular foreclosure process may halt. However, in the event you continue to miss out on payments within the new program, the property foreclosures process can just pick up from where it was left off.

  16. I like what you guys are up too. Such intelligent work and reporting! Keep up the superb works guys I?ve incorporated you guys to my blogroll. I think it will improve the value of my site 🙂

  17. I was more than happy to seek out this internet-site.I wished to thanks in your time for this wonderful read!! I definitely having fun with every little bit of it and I’ve you bookmarked to check out new stuff you weblog post.

  18. Thank you for the auspicious writeup. It actually was a amusement account it. Look complicated to far delivered agreeable from you! However, how could we be in contact?

  19. Thanks for the auspicious writeup. It in fact used to be a amusement account it. Look complex to far added agreeable from you! However, how can we keep up a correspondence?

  20. I’ve learned a number of important things by means of your post. I will also like to convey that there might be situation where you will make application for a loan and don’t need a cosigner such as a Government Student Support Loan. When you are getting credit through a common bank then you need to be made ready to have a co-signer ready to allow you to. The lenders will probably base that decision on the few issues but the largest will be your credit history. There are some creditors that will also look at your job history and make a decision based on that but in most cases it will be based on on your ranking.

  21. Thank you for another informative blog. Where else could I get that kind of information written in such an ideal way? I’ve a project that I am just now working on, and I have been on the look out for such information.

  22. Attractive element of content. I just stumbled upon your web site and in accession capital to say that I acquire in fact enjoyed account your blog posts. Anyway I?ll be subscribing for your augment and even I success you get entry to constantly rapidly.

  23. A further issue is really that video gaming has become one of the all-time biggest forms of entertainment for people of every age group. Kids participate in video games, plus adults do, too. The particular XBox 360 is among the favorite video games systems for those who love to have a lot of games available to them, in addition to who like to learn live with people all over the world. Many thanks for sharing your ideas.

  24. Superb post however I was wanting to know if you could write a litte more on this subject? I’d be very grateful if you could elaborate a little bit more. Many thanks!

  25. I really like your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to design my own blog and would like to know where u got this from. appreciate it

  26. It?s exhausting to search out educated people on this topic, but you sound like you know what you?re talking about! Thanks

  27. certainly like your website however you need to test the spelling on several of your posts. Several of them are rife with spelling problems and I find it very bothersome to inform the reality however I?ll surely come back again.

  28. I would like to thnkx for the efforts you’ve put in writing this blog. I am hoping the same high-grade website post from you in the upcoming also. In fact your creative writing skills has encouraged me to get my own web site now. Really the blogging is spreading its wings quickly. Your write up is a great example of it.

  29. Another thing I have really noticed is that often for many people, below-average credit is the reaction to circumstances above their control. For example they may be actually saddled having an illness so they really have higher bills going to collections. It might be due to a occupation loss or perhaps the inability to work. Sometimes divorce proceedings can send the money in the undesired direction. Many thanks for sharing your ideas on this blog site.

  30. Hi there, You have done a great job. I will certainly digg it and personally suggest to my friends. I am confident they will be benefited from this web site.

發佈留言

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