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

  1. Hey just wanted to give you a brief heads up and let you know a few of the images aren’t loading correctly. 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 results.

  2. Thanks for the ideas you have contributed here. Additionally, I believe there are numerous factors which really keep your automobile insurance premium lower. One is, to consider buying cars and trucks that are inside the good list of car insurance businesses. Cars that happen to be expensive will be more at risk of being robbed. Aside from that insurance is also in line with the value of your vehicle, so the higher priced it is, then the higher this premium you pay.

  3. Thanks for your posting. One other thing is the fact individual states in the United states of america have their very own laws that affect home owners, which makes it quite hard for the our lawmakers to come up with a different set of rules concerning foreclosure on householders. The problem is that every state features own regulations which may have impact in an unwanted manner with regards to foreclosure policies.

  4. Hey there! Do you use Twitter? I’d like to follow you if that would be okay. I’m undoubtedly enjoying your blog and look forward to new posts.

  5. Good day! I could have sworn I’ve been to this blog before but after reading through some of the post I realized it’s new to me. Nonetheless, I’m definitely happy I found it and I’ll be bookmarking and checking back frequently!

  6. I’ve learned many important things by means of your post. I might also like to state that there may be situation where you will obtain a loan and don’t need a cosigner such as a Federal government Student Support Loan. However, if you are getting that loan through a regular loan company then you need to be ready to have a co-signer ready to enable you to. The lenders are going to base that decision using a few factors but the main one will be your credit worthiness. There are some financial institutions that will as well look at your job history and choose based on this but in almost all cases it will depend on your ranking.

  7. Hello there! I know this is kinda off topic however , I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa? My blog goes over a lot of the same topics as yours and I believe we could greatly benefit from each other. If you’re interested feel free to shoot me an e-mail. I look forward to hearing from you! Superb blog by the way!

  8. Thanks for another wonderful post. The place else may just anyone get that kind of info in such a perfect manner of writing? I have a presentation subsequent week, and I am at the look for such info.

  9. Oh my goodness! an amazing article dude. Thank you Nonetheless I am experiencing challenge with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting equivalent rss downside? Anybody who knows kindly respond. Thnkx

  10. An additional issue is that video gaming has become one of the all-time most important forms of excitement for people spanning various ages. Kids participate in video games, plus adults do, too. Your XBox 360 is among the favorite gaming systems for those who love to have a lot of video games available to them, along with who like to experiment with live with people all over the world. Many thanks for sharing your ideas.

  11. Thanks for your information on this blog. Just one thing I would want to say is that purchasing gadgets items through the Internet is certainly not new. In truth, in the past decades alone, the market for online electronic products has grown considerably. Today, you will discover practically any specific electronic gadget and other gadgets on the Internet, from cameras as well as camcorders to computer elements and video games consoles.

  12. What an eye-opening and meticulously-researched article! The author’s meticulousness and ability to present intricate ideas in a digestible manner is truly commendable. I’m extremely impressed by the breadth of knowledge showcased in this piece. Thank you, author, for providing your wisdom with us. This article has been a game-changer!

  13. Does your website have a contact page? I’m having problems locating it but, I’d like to shoot you an e-mail. I’ve got some ideas for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it grow over time.

  14. Whoa! This blog looks exactly like my old one! It’s on a completely different subject but it has pretty much the same layout and design. Outstanding choice of colors!

  15. Awesome blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple tweeks would really make my blog shine. Please let me know where you got your theme. Appreciate it

  16. of course like your web site but you need to check the spelling on several of your posts. A number of them are rife with spelling problems and I find it very bothersome to tell the truth nevertheless I will certainly come back again.

  17. I like the helpful information you provide in your articles. I?ll bookmark your blog and check again here frequently. I am quite certain I?ll learn many new stuff right here! Good luck for the next!

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

  19. There are some interesting points in time in this article however I don?t know if I see all of them center to heart. There’s some validity however I’ll take hold opinion until I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as properly

  20. Have you ever considered about including a little bit more than just your articles? I mean, what you say is valuable and all. However just imagine if you added some great visuals or videos to give your posts more, “pop”! Your content is excellent but with pics and videos, this blog could certainly be one of the most beneficial in its field. Fantastic blog!

  21. Just wish to say your article is as astonishing. The clarity on your put up is simply great and that i could think you are an expert in this subject. Well together with your permission allow me to take hold of your RSS feed to stay updated with coming near near post. Thanks 1,000,000 and please keep up the gratifying work.

  22. One thing I’d really like to say is that often car insurance cancellation is a dreaded experience so if you’re doing the proper things as a driver you simply won’t get one. Some people do get the notice that they are officially dumped by the insurance company and several have to struggle to get additional insurance from a cancellation. Low cost auto insurance rates are generally hard to get from a cancellation. Knowing the main reasons concerning the auto insurance canceling can help owners prevent completely losing in one of the most important privileges out there. Thanks for the tips shared by your blog.

  23. I liked as much as you will receive performed right here. The cartoon is attractive, your authored material stylish. nevertheless, you command get got an edginess over that you want be handing over the following. unwell unquestionably come more before once more as precisely the similar just about very ceaselessly within case you defend this hike.

  24. I have not checked in here for a while because I thought it was getting boring, but the last several posts are great quality so I guess I?ll add you back to my daily bloglist. You deserve it my friend 🙂

  25. I have read some excellent stuff here. Certainly worth bookmarking for revisiting. I wonder how so much effort you set to create one of these great informative web site.

  26. After I initially commented I clicked the -Notify me when new feedback are added- checkbox and now each time a remark is added I get four emails with the same comment. Is there any manner you possibly can remove me from that service? Thanks!

  27. 1xbet_xaEt表示:

    1xbet: ваш билет к крупным выигрышам, 1xbet радует своих клиентов щедрыми бонусами и акциями, 1xbet – доверьте свои ставки профессионалам, 1xbet гарантирует мгновенные выплаты и безопасные транзакции, 1xbet: все виды ставок на любой вкус, 1xbet: доступ к лучшим матчам и событиям, 1xbet ценит каждого клиента и предлагает первоклассное обслуживание, 1xbet радует своих клиентов высокими коэффициентами и шансами на победу, 1xbet приглашает всех желающих испытать свою удачу и выиграть большой джекпот, 1xbet: надежный партнер для ставок на спорт, 1xbet – это комфорт и удобство для игроков, 1xbet: любимый букмекер миллионов, 1xbet: лучший выбор для ставок на любимые команды, 1xbet – ваш надежный партнер в мире ставок, 1xbet – ваш выбор для выигрышных ставок, 1xbet – ваш путь к мировому успеху в ставках, 1xbet: ультрасовременные технологии и инновации, 1xbet – ваш выбор для успешных ставок.
    1xbet x 1xbet x .

  28. I was wondering if you ever thought of changing the layout of your website? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or 2 pictures. Maybe you could space it out better?

  29. I have been exploring for a bit for any high-quality articles or blog posts on this kind of area . Exploring in Yahoo I at last stumbled upon this website. Reading this information So i am happy to convey that I have an incredibly good uncanny feeling I discovered just what I needed. I most certainly will make certain to do not forget this site and give it a look on a constant basis.

發佈留言

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