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

  1. One thing is one of the most widespread incentives for using your cards is a cash-back or perhaps rebate offer. Generally, you will get 1-5 back upon various acquisitions. Depending on the credit cards, you may get 1 returning on most acquisitions, and 5 back on expenditures made on convenience stores, gasoline stations, grocery stores as well as ‘member merchants’.

  2. Yet another issue is really that video gaming became one of the all-time biggest forms of entertainment for people spanning various ages. Kids play video games, and adults do, too. The actual XBox 360 has become the favorite gaming systems for many who love to have hundreds of video games available to them, and also who like to play live with people all over the world. Thanks for sharing your thinking.

  3. En iyi kumarhanede buyuk kazan?n Sweet bonanza

  4. Excellent post. I was checking constantly this blog and I’m impressed! Very helpful info specially the last part 🙂 I care for such info much. I was seeking this certain information for a long time. Thank you and good luck.

  5. I just like the valuable information you supply for your articles. I?ll bookmark your blog and check once more here regularly. I’m rather certain I?ll be informed plenty of new stuff right here! Best of luck for the following!

  6. It’s a pity you don’t have a donate button! I’d definitely donate to this excellent blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to fresh updates and will talk about this website with my Facebook group. Chat soon!

  7. One more thing. I think that there are several travel insurance websites of reliable companies that allow you enter a trip details and find you the rates. You can also purchase your international holiday insurance policy on the internet by using your own credit card. Everything you need to do is always to enter the travel specifics and you can begin to see the plans side-by-side. Just find the program that suits your capacity to pay and needs and use your bank credit card to buy the item. Travel insurance online is a good way to take a look for a reliable company regarding international travel insurance. Thanks for expressing your ideas.

  8. Herkesin tavsiye ettigi kumarhane Sweet bonanza

  9. En unlu kumarhanede sans?n?z? deneyin Sweet bonanza

  10. I?m impressed, I must say. Actually not often do I encounter a blog that?s both educative and entertaining, and let me inform you, you will have hit the nail on the head. Your idea is outstanding; the issue is one thing that not sufficient persons are speaking intelligently about. I’m very glad that I stumbled across this in my search for one thing regarding this.

  11. Unquestionably believe that which you stated. Your favorite reason appeared to be on the web the simplest thing to be aware of. I say to you, I definitely get irked while people consider 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 could take a signal. Will likely be back to get more. Thanks

  12. I found your weblog website on google and test just a few of your early posts. Continue to maintain up the very good operate. I simply further up your RSS feed to my MSN Information Reader. Searching for forward to studying extra from you later on!?

  13. hello there and thank you to your information ? I?ve definitely picked up something new from proper here. I did on the other hand expertise some technical points using this website, as I skilled to reload the web site a lot of occasions previous to I may just get it to load properly. I have been considering if your web hosting is OK? Not that I’m complaining, but sluggish loading instances instances will sometimes affect your placement in google and can damage your high-quality score if advertising and ***********|advertising|advertising|advertising and *********** with Adwords. Well I?m including this RSS to my e-mail and can glance out for a lot extra of your respective interesting content. Make sure you update this again soon..

  14. Hey there I am so grateful I found your blog page, I really found you by error, while I was researching on Google for something else, Regardless I am here now and would just like to say cheers for a incredible post and a all round thrilling blog (I also love the theme/design), I don’t have time to read it all at the moment but I have bookmarked it and also added in your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the awesome job.

  15. I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following. unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this increase.

  16. Smsakobliz表示:

    Сервис виртуальной смс активации номера – Smsak

  17. You could definitely see your expertise in the work you write. The world hopes for even more passionate writers like you who are not afraid to say how they believe. Always go after your heart.

  18. It?s arduous to find educated individuals on this subject, however you sound like you realize what you?re speaking about! Thanks

  19. I was just looking for this information for a while. After 6 hours of continuous Googleing, at last I got it in your website. I wonder what’s the lack of Google strategy that do not rank this type of informative websites in top of the list. Usually the top sites are full of garbage.

  20. Thanks for your post. I have often observed that a majority of people are eager to lose weight as they wish to look slim as well as attractive. Nevertheless, they do not usually realize that there are many benefits so that you can losing weight also. Doctors claim that over weight people experience a variety of diseases that can be directly attributed to their particular excess weight. The great news is that people who are overweight and suffering from diverse diseases are able to reduce the severity of their own illnesses simply by losing weight. You’ll be able to see a continuous but identifiable improvement with health as soon as even a negligible amount of fat reduction is attained.

  21. I?m not sure where you’re getting your information, but great topic. I needs to spend some time learning more or understanding more. Thanks for wonderful information I was looking for this info for my mission.

  22. Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you can do with a few pics to drive the message home a little bit, but other than that, this is great blog. A great read. I will certainly be back.

  23. Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how can we communicate?

  24. Aw, this was a very nice post. In concept I would like to put in writing like this moreover ? taking time and precise effort to make an excellent article? but what can I say? I procrastinate alot and not at all seem to get one thing done.

  25. cbd massage表示:

    Very good site you have here but I was curious about if you knew of any message boards that cover the same topics discussed here? I’d really love to be a part of group where I can get comments from other experienced individuals that share the same interest. If you have any suggestions, please let me know. Thank you!

  26. En guvenilir online casino Sweet bonanza

  27. I like the valuable information you provide in your articles. I will bookmark your blog and check again here regularly. I’m quite certain I?ll learn a lot of new stuff right here! Best of luck for the next!

  28. cbd massage表示:

    This article is absolutely incredible! The author has done a tremendous job of conveying the information in an compelling and informative manner. I can’t thank him enough for offering such precious insights that have certainly enlightened my awareness in this subject area. Hats off to her for producing such a masterpiece!

  29. Thx for your post. I’d really like to say that the expense of car insurance will vary from one plan to another, simply because there are so many different facets which contribute to the overall cost. One example is, the make and model of the car will have an enormous bearing on the price. A reliable older family auto will have a more economical premium when compared to a flashy sports car.

發佈留言

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