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

  1. I would also like to add that when you do not currently have an insurance policy or you do not form part of any group insurance, you could possibly well gain from seeking the help of a health insurance agent. Self-employed or those with medical conditions typically seek the help of an health insurance brokerage. Thanks for your blog post.

  2. Hello there! I know this is kind of off topic but I was wondering which blog platform are you using for this website? I’m getting sick and tired of WordPress because I’ve had issues with hackers and I’m looking at options for another platform. I would be fantastic if you could point me in the direction of a good platform.

  3. li ruo jia表示:

    Hi there! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

  4. Great site! I recommend it to everyone!Book private flights

  5. Hi there, simply turned into aware of your blog via Google, and found that it is truly informative. I?m gonna be careful for brussels. I?ll appreciate when you continue this in future. Many other people will likely be benefited out of your writing. Cheers!

  6. It is my belief that mesothelioma is definitely the most dangerous cancer. It contains unusual attributes. The more I really look at it the more I am assured it does not behave like a real solid tissues cancer. In case mesothelioma is a rogue virus-like infection, hence there is the chance of developing a vaccine in addition to offering vaccination to asbestos uncovered people who are open to high risk of developing future asbestos linked malignancies. Thanks for sharing your ideas about this important ailment.

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

  8. I’ve noticed that credit score improvement activity has to be conducted with techniques. If not, you will probably find yourself damaging your rank. In order to succeed in fixing your credit score you have to ensure that from this minute you pay your complete monthly costs promptly before their booked date. It really is significant given that by not accomplishing that, all other steps that you will decide on to improve your credit ranking will not be successful. Thanks for expressing your strategies.

  9. Youre so cool! I dont suppose Ive read something like this before. So nice to seek out someone with some authentic ideas on this subject. realy thanks for beginning this up. this web site is something that is wanted on the web, someone with a little originality. helpful job for bringing something new to the web!

  10. Leonardpar表示:

    http://edpillpharmacy.store/# affordable ed medication

  11. DouglasGed表示:

    medication from mexico pharmacy: mexican online pharmacies prescription drugs – mexican pharmaceuticals online

  12. Thanks for these guidelines. One thing I additionally believe is always that credit cards featuring a 0 apr often attract consumers in zero monthly interest, instant authorization and easy online balance transfers, but beware of the number one factor that will void that 0 easy road annual percentage rate and also throw anybody out into the bad house quickly.

  13. DouglasGed表示:

    mexican drugstore online: mexican pharmacy – reputable mexican pharmacies online

  14. DouglasGed表示:

    online ed meds: ed prescription online – where can i get ed pills

  15. I have observed that over the course of building a relationship with real estate owners, you’ll be able to come to understand that, in each and every real estate contract, a commission is paid. Eventually, FSBO sellers do not “save” the commission payment. Rather, they struggle to win the commission simply by doing a good agent’s occupation. In doing this, they commit their money plus time to carry out, as best they’re able to, the obligations of an adviser. Those tasks include disclosing the home by marketing, showing the home to willing buyers, constructing a sense of buyer urgency in order to induce an offer, organizing home inspections, taking on qualification check ups with the bank, supervising maintenance, and assisting the closing.

  16. Hi there, I discovered your web site by the use of Google at the same time as looking for a comparable matter, your website got here up, it seems to be good. I have bookmarked it in my google bookmarks.

  17. I just added this site to my google reader, great stuff. Cannot get enough!

  18. Sweet blog! I found it while searching on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Thank you

  19. I’m usually to running a blog and i really recognize your content. The article has really peaks my interest. I am going to bookmark your web site and maintain checking for brand new information.

  20. Hey there, You have done a fantastic job. I will certainly digg it and personally suggest to my friends. I am sure they will be benefited from this website.

  21. I do not even understand how I stopped up here, but I assumed this submit was once good. I do not understand who you’re but certainly you are going to a famous blogger for those who are not already 😉 Cheers!

  22. u91220151表示:

    Thanks for another excellent post. The place else could anybody get that kind of info in such a perfect approach of writing? I’ve a presentation next week, and I am on the look for such information.

  23. Great ? I should certainly pronounce, impressed with your website. I had no trouble navigating through all tabs as well as related information ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, web site theme . a tones way for your client to communicate. Excellent task..

  24. Hi! Would you mind if I share your blog with my zynga group? There’s a lot of folks that I think would really enjoy your content. Please let me know. Many thanks

  25. I have read some good stuff here. Certainly worth bookmarking for revisiting. I wonder how much effort you put to make such a wonderful informative site.

  26. Many thanks for sharing most of these wonderful discussions. In addition, the best travel as well as medical insurance program can often relieve those problems that come with travelling abroad. Any medical emergency can rapidly become very costly and that’s sure to quickly impose a financial problem on the family finances. Setting up in place the best travel insurance bundle prior to setting off is definitely worth the time and effort. Thank you

  27. Good site! I really love how it is simple on my eyes and the data are well written. I am wondering how I could be notified when a new post has been made. I’ve subscribed to your feed which must do the trick! Have a nice day!

  28. I have acquired some new things from your web page about computers. Another thing I’ve always imagined is that laptop computers have become a specific thing that each house must have for most reasons. They provide convenient ways to organize households, pay bills, go shopping, study, pay attention to music as well as watch shows. An innovative solution to complete most of these tasks is with a computer. These computers are mobile, small, powerful and mobile.

發佈留言

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