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

  1. okmark your blog and check again here frequently. I’m quite certain I?ll learn plenty of new stuff right here! Best of luck for the next!

  2. I figured out more new things on this fat loss issue. One issue is that good nutrition is tremendously vital whenever dieting. A big reduction in junk food, sugary meals, fried foods, sweet foods, pork, and white colored flour products could be necessary. Having wastes bloodsuckers, and toxins may prevent goals for shedding fat. While a number of drugs momentarily solve the situation, the bad side effects will not be worth it, and in addition they never present more than a short-term solution. It can be a known idea that 95 of diet plans fail. Many thanks sharing your opinions on this website.

  3. Its like you read my thoughts! You appear to understand a lot about this, such as you wrote the e book in it or something. I feel that you could do with a few to power the message home a bit, however other than that, this is wonderful blog. A great read. I’ll definitely be back.

  4. I think this is among the most significant info for me. And i’m glad reading your article. But want to remark on some general things, The web site style is ideal, the articles is really excellent : D. Good job, cheers

  5. Good write-up, I am normal visitor of one?s website, maintain up the nice operate, and It’s going to be a regular visitor for a lengthy time.

  6. A person necessarily lend a hand to make seriously posts I would state. That is the first time I frequented your web page and up to now? I surprised with the research you made to make this actual post extraordinary. Wonderful activity!

  7. noonn_28 porn表示:

    One other issue is that if you are in a circumstance where you do not have a cosigner then you may actually want to try to wear out all of your money for college options. You can get many grants and other grants that will ensure that you get finances that can help with institution expenses. Thank you for the post.

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

  9. In accordance with my observation, after a foreclosed home is marketed at an auction, it is common for the borrower to be able to still have the remaining unpaid debt on the mortgage. There are many financial institutions who attempt to have all charges and liens paid by the next buyer. Having said that, depending on specific programs, rules, and state legal guidelines there may be many loans which aren’t easily settled through the switch of financial products. Therefore, the obligation still falls on the debtor that has acquired his or her property foreclosed on. Many thanks sharing your opinions on this site.

  10. Hey! This post could not be written any better! Reading this post reminds me of my old room mate! He always kept chatting about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!

  11. Today, taking into consideration the fast lifestyle that everyone leads, credit cards have a huge demand in the economy. Persons out of every discipline are using the credit card and people who aren’t using the credit cards have arranged to apply for 1. Thanks for sharing your ideas in credit cards.

  12. I am curious to find out what blog system you have been working with? I’m having some minor security problems with my latest blog and I would like to find something more safeguarded. Do you have any recommendations?

  13. One thing I would really like to say is the fact that before obtaining more computer memory, have a look at the machine in to which it is installed. In case the machine will be running Windows XP, for instance, the actual memory ceiling is 3.25GB. Putting in a lot more than this would merely constitute some sort of waste. Make certain that one’s mother board can handle the actual upgrade amount, as well. Good blog post.

  14. Many thanks for this article. I’d personally also like to state that it can always be hard when you are in school and starting out to create a long credit score. There are many pupils who are just trying to make it and have a long or positive credit history can sometimes be a difficult element to have.

  15. Dnrtsky表示:

    Привет, друзья!
    Приобрести документ о получении высшего образования можно в нашей компании.
    obmenka.forum2x2.ru/t16293-topic#37488

  16. I do trust all the ideas you have introduced on your post. They are very convincing and can certainly work. Still, the posts are too brief for novices. May you please prolong them a little from subsequent time? Thank you for the post.

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

  18. excellent points altogether, you simply gained a brand new reader. What would you recommend about your post that you made some days ago? Any positive?

  19. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three e-mails with the same comment. Is there any way you can remove me from that service? Thanks a lot!

  20. Great items from you, man. I have remember your stuff previous to and you’re simply too fantastic. I really like what you’ve received right here, certainly like what you’re stating and the way in which by which you are saying it. You are making it entertaining and you continue to take care of to stay it sensible. I cant wait to learn much more from you. This is actually a great site.

  21. Stanleyinolf表示:

    40 mg lisinopril Lisinopril refill online lisinopril 20 12.5 mg

  22. Thanks for the helpful content. It is also my belief that mesothelioma has an particularly long latency interval, which means that signs of the disease may not emerge right until 30 to 50 years after the first exposure to mesothelioma. Pleural mesothelioma, and that is the most common form and has an effect on the area within the lungs, may cause shortness of breath, upper body pains, along with a persistent cough, which may result in coughing up bloodstream.

  23. This article is a refreshing change! The author’s unique perspective and insightful analysis have made this a truly fascinating read. I’m thankful for the effort she has put into producing such an enlightening and provocative piece. Thank you, author, for sharing your expertise and stimulating meaningful discussions through your outstanding writing!

  24. 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 view, if all web owners and bloggers made good content as you did, the net will be a lot more useful than ever before.

  25. Hiya! I simply wish to give an enormous thumbs up for the great info you might have right here on this post. I will likely be coming again to your blog for more soon.

  26. I have witnessed that costs for on-line degree specialists tend to be a great value. For example a full 4-year college Degree in Communication with the University of Phoenix Online consists of 60 credits from $515/credit or $30,900. Also American Intercontinental University Online offers a Bachelors of Business Administration with a whole program element of 180 units and a tuition fee of $30,560. Online learning has made taking your college degree been so detailed more than before because you can certainly earn your degree through the comfort of your home and when you finish from office. Thanks for other tips I have certainly learned through your blog.

  27. With havin so much written content do you ever run into any issues of plagorism or copyright infringement? My blog has a lot of 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 permission. Do you know any ways to help reduce content from being ripped off? I’d definitely appreciate it.

  28. I?ve read several good stuff here. Certainly worth bookmarking for revisiting. I wonder how much effort you put to make such a magnificent informative web site.

  29. Hmm it seems like your blog ate my first comment (it was super long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I too am an aspiring blog writer but I’m still new to everything. Do you have any helpful hints for inexperienced blog writers? I’d really appreciate it.

  30. Woah! I’m really enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between user friendliness and appearance. I must say that you’ve done a fantastic job with this. Also, the blog loads extremely fast for me on Opera. Excellent Blog!

發佈留言

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