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

  1. Dinogame.app表示:

    Terrific post however , I was wondering if you could write a litte more on this topic? I’d be very grateful if you could elaborate a little bit more. Many thanks!

  2. Dinogame.app表示:

    Hey very nice blog!! Man .. Excellent .. Amazing .. I will bookmark your blog and take the feeds also?I’m happy to find so many useful info here in the post, we need work out more strategies in this regard, thanks for sharing. . . . . .

  3. Dinogame.app表示:

    Wonderful web site. A lot of useful info here. I?m sending it to a few buddies ans additionally sharing in delicious. And naturally, thank you in your effort!

  4. Dinogame.app表示:

    I believe this is among the such a lot significant information for me. And i’m satisfied studying your article. However want to commentary on few general things, The web site taste is perfect, the articles is truly excellent : D. Excellent task, cheers

  5. Dinogame.app表示:

    Have you ever considered creating an ebook or guest authoring on other websites? I have a blog centered on the same subjects you discuss and would really like to have you share some stories/information. I know my subscribers would enjoy your work. If you are even remotely interested, feel free to send me an e-mail.

  6. Dinogame.app表示:

    Great work! That is the type of information that are supposed to be shared across the web. Disgrace on the seek engines for now not positioning this submit higher! Come on over and seek advice from my web site . Thank you =)

  7. Dinogame.app表示:

    This is undoubtedly one of the greatest articles I’ve read on this topic! The author’s extensive knowledge and passion for the subject are evident in every paragraph. I’m so appreciative for finding this piece as it has deepened my comprehension and ignited my curiosity even further. Thank you, author, for taking the time to produce such a outstanding article!

  8. Dinogame.app表示:

    Good day! I know this is somewhat off topic but I was wondering if you knew where I could find a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one? Thanks a lot!

  9. Dinogame.app表示:

    I have noticed that online diploma is getting favorite because attaining your college degree online has become a popular solution for many people. A huge number of people have not really had a possibility to attend a regular college or university nevertheless seek the improved earning potential and career advancement that a Bachelor’s Degree gives you. Still others might have a diploma in one discipline but would want to pursue something they now develop an interest in.

  10. Dinogame.app表示:

    After I originally commented I clicked the -Notify me when new comments are added- checkbox and now every time a comment is added I get four emails with the same comment. Is there any method you can remove me from that service? Thanks!

  11. Dinogame.app表示:

    I?ve read some good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to create such a fantastic informative web site.

  12. Dinogame.app表示:

    It is actually a great and useful piece of info. I am glad that you simply shared this helpful info with us. Please keep us informed like this. Thanks for sharing.

  13. Dinogame.app表示:

    Hey! Do you know if they make any plugins to help with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success. If you know of any please share. Thanks!

  14. Bppumq表示:

    buy monograph online cheap – purchase pletal online cheap order cilostazol

  15. Dinogame.app表示:

    Yet another thing is that when searching for a good on the net electronics retail outlet, look for online shops that are continuously updated, preserving up-to-date with the newest products, the most effective deals, in addition to helpful information on products and services. This will ensure you are getting through a shop which stays ahead of the competition and give you what you need to make knowledgeable, well-informed electronics acquisitions. Thanks for the significant tips I have really learned through the blog.

  16. Dinogame.app表示:

    Howdy, i read your blog from time to time and i own a similar one and i was just curious if you get a lot of spam comments? If so how do you prevent it, any plugin or anything you can recommend? I get so much lately it’s driving me crazy so any assistance is very much appreciated.

  17. Ismaelfer表示:

    This info is invaluable. Where can I find out more?
    http://http://musey-uglich.ru/

  18. Dinogame.app表示:

    Good blog post. The things i would like to make contributions about is that laptop or computer memory must be purchased but if your computer can’t cope with what you do along with it. One can put in two RAM boards having 1GB each, by way of example, but not certainly one of 1GB and one with 2GB. One should check the manufacturer’s documentation for one’s PC to make sure what type of memory space it can take.

  19. Dinogame.app表示:

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

  20. Dinogame.app表示:

    Woah! I’m really digging the template/theme of this blog. It’s simple, yet effective. A lot of times it’s hard to get that “perfect balance” between superb usability and visual appeal. I must say that you’ve done a excellent job with this. In addition, the blog loads extremely fast for me on Opera. Outstanding Blog!

  21. Dinogame.app表示:

    I think this is among the most important information for me. And i’m glad reading your article. But wanna remark on some general things, The website style is perfect, the articles is really great : D. Good job, cheers

  22. Dinogame.app表示:

    I was suggested this website by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my difficulty. You are wonderful! Thanks!

  23. Dinogame.app表示:

    Another issue is that video games usually are serious naturally with the primary focus on mastering rather than enjoyment. Although, we have an entertainment part to keep the kids engaged, every single game is normally designed to develop a specific set of skills or course, such as math concepts or technology. Thanks for your write-up.

  24. Dinogame.app表示:

    Please let me know if you’re looking for a writer for your blog. You have some really good articles and I believe I would be a good asset. If you ever want to take some of the load off, I’d really like to write some articles for your blog in exchange for a link back to mine. Please blast me an e-mail if interested. Thanks!

  25. Dinogame.app表示:

    Hey there would you mind letting me know which hosting company you’re using? I’ve loaded your blog in 3 completely different internet browsers and I must say this blog loads a lot quicker then most. Can you suggest a good hosting provider at a honest price? Thank you, I appreciate it!

  26. Dinogame.app表示:

    Definitely believe that which you stated. Your favorite justification seemed to be on the net the easiest thing to be aware of. I say to you, I definitely get annoyed while people think about worries that they just do not know about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks

  27. Dinogame.app表示:

    Somebody necessarily lend a hand to make critically articles I’d state. That is the first time I frequented your web page and thus far? I surprised with the analysis you made to create this particular publish incredible. Magnificent activity!

  28. Tente sua sorte no melhor cassino Blaze

發佈留言

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