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...

16,757 Responses

  1. Thanks a lot for sharing this with all of us you actually know what you’re talking about! Bookmarked. Kindly also visit my web site =). We could have a link exchange agreement between us!

  2. GlennSnofs表示:

    ed therapy canadiandrugsgate dog antibiotics without vet prescription

  3. I discovered your weblog web site on google and test just a few of your early posts. Proceed to maintain up the excellent operate. I simply additional up your RSS feed to my MSN Information Reader. Looking for ahead to reading more from you in a while!?

  4. Hey there, You’ve done a fantastic job. I will definitely digg it and personally recommend to my friends. I am sure they will be benefited from this website.

  5. I have discovered that intelligent real estate agents everywhere are getting set to FSBO ***********. They are acknowledging that it’s in addition to placing a sign post in the front area. It’s really about building connections with these retailers who at some time will become customers. So, while you give your time and efforts to helping these sellers go it alone : the “Law of Reciprocity” kicks in. Great blog post.

  6. промокод на подключение продамуса prodamus-promokod21.ru .

  7. kaizenaire表示:

    Wonderful work! That is the kind of info that should be shared across the web. Disgrace on the seek engines for no longer positioning this submit upper! Come on over and discuss with my site . Thanks =)

  8. xnxxrush.com表示:

    Verry quickly this weeb pave wilpl bbe famous among all blogging andd site-building people, due to it’s ice articles orr reviews

  9. kaizenaire表示:

    Hi, I think your website might be having browser compatibility issues. When I look at your blog in Chrome, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, great blog!

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

  11. Jamiecaw表示:

    https://mexicanpharmgate.com/# п»їbest mexican online pharmacies

  12. whoah this blog is fantastic i love studying your posts. Stay up the great work! You recognize, a lot of people are searching around for this information, you can aid them greatly.

  13. Thanks for the recommendations shared on your own blog. Yet another thing I would like to talk about is that weight reduction is not all about going on a fad diet and trying to reduce as much weight that you can in a couple of days. The most effective way to lose weight naturally is by having it little by little and right after some basic guidelines which can provide help to make the most out of your attempt to lose fat. You may understand and already be following most of these tips, however reinforcing expertise never affects.

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

  15. kaizenaire表示:

    Unquestionably believe that that you said. Your favourite reason seemed to be at the net the simplest factor to take into accout of. I say to you, I certainly get annoyed even as folks consider worries that they plainly don’t understand about. You controlled to hit the nail upon the top as neatly as outlined out the whole thing without having side effect , other folks can take a signal. Will probably be again to get more. Thanks

  16. I truly appreciate this post. I have been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thx again

  17. нарколог на дом вывод из запоя на дому нарколог на дом вывод из запоя на дому .

  18. вывод из запоя на дому ростов недорого http://www.forumbar.anihub.me/viewtopic.php?id=9747 .

  19. I have learned some new things as a result of your web site. One other thing I want to say is that often newer personal computer os’s are inclined to allow much more memory for use, but they in addition demand more memory space simply to function. If your computer is unable to handle extra memory along with the newest software requires that storage increase, it is usually the time to shop for a new Computer system. Thanks

  20. Thanks a bunch for sharing this with all of us you actually know what you are talking about! Bookmarked. Kindly also visit my web site =). We could have a link exchange contract between us!

  21. вывод из запоя в ростове-на-дону [url=www.to.iboard.ws/viewtopic.php?id=8058/]www.to.iboard.ws/viewtopic.php?id=8058/[/url] .

  22. What an eye-opening and well-researched article! The author’s attention to detail and ability to present complex ideas in a comprehensible manner is truly praiseworthy. I’m extremely impressed by the depth of knowledge showcased in this piece. Thank you, author, for offering your wisdom with us. This article has been a real game-changer!

  23. вывод из запоя ростов и область [url=gonochki.forum24.ru/?1-10-0-00001128-000-0-0-1730649505]вывод из запоя ростов и область[/url] .

  24. It’s a pity you don’t have a donate button! I’d definitely donate to this fantastic blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to brand new updates and will share this site with my Facebook group. Chat soon!

  25. kaizenaire表示:

    An impressive share, I just given this onto a colleague who was doing a bit of analysis on this. And he the truth is purchased me breakfast because I found it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love studying extra on this topic. If attainable, as you develop into experience, would you mind updating your weblog with extra particulars? It’s extremely useful for me. Massive thumb up for this blog put up!

發佈留言

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