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

  1. Hi there! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly? My weblog looks weird when browsing from my iphone 4. I’m trying to find a theme or plugin that might be able to correct this issue. If you have any recommendations, please share. Cheers!

  2. Generally I don’t read post on blogs, but I wish to say that this write-up very forced me to try and do it! Your writing style has been surprised me. Thanks, very nice post.

  3. I like what you guys are up too. Such clever work and reporting! Keep up the excellent works guys I?ve incorporated you guys to my blogroll. I think it will improve the value of my site 🙂

  4. Fantastic blog! Do you have any hints for aspiring writers? I’m hoping to start my own site soon but I’m a little lost on everything. Would you propose starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely confused .. Any tips? Thank you!

  5. I believe that avoiding processed foods will be the first step so that you can lose weight. They could taste very good, but prepared foods currently have very little vitamins and minerals, making you try to eat more simply to have enough strength to get through the day. When you are constantly ingesting these foods, changing to grain and other complex carbohydrates will aid you to have more vigor while ingesting less. Thanks alot : ) for your blog post.

  6. Magnificent website. A lot of useful information here. I am sending it to a few buddies ans additionally sharing in delicious. And obviously, thank you in your sweat!

  7. Thank you, I have just been searching for information about this topic for ages and yours is the best I’ve discovered till now. But, what about the conclusion? Are you sure about the source?

  8. Great write-up, I am normal visitor of one?s web site, maintain up the excellent operate, and It’s going to be a regular visitor for a long time.

  9. Hi! Would you mind if I share your blog with my twitter group? There’s a lot of people that I think would really appreciate your content. Please let me know. Cheers

  10. A person necessarily help to make critically articles I might state. That is the first time I frequented your website page and up to now? I surprised with the analysis you made to create this actual post extraordinary. Fantastic job!

  11. Thanks for the suggestions you are discussing on this site. Another thing I want to say is the fact that getting hold of duplicates of your credit history in order to check out accuracy of each detail is the first measures you have to carry out in credit restoration. You are looking to thoroughly clean your credit reports from destructive details problems that mess up your credit score.

  12. After study a couple of of the blog posts on your web site now, and I actually like your way of blogging. I bookmarked it to my bookmark website record and will likely be checking back soon. Pls take a look at my website as effectively and let me know what you think.

  13. Hello! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My web site looks weird when viewing from my apple iphone. I’m trying to find a theme or plugin that might be able to fix this issue. If you have any recommendations, please share. Thank you!

  14. Thanks for your posting. What I want to point out is that while searching for a good internet electronics go shopping, look for a web-site with full information on critical factors such as the level of privacy statement, basic safety details, any payment options, along with other terms and policies. Often take time to browse the help as well as FAQ pieces to get a greater idea of how a shop is effective, what they can do for you, and in what way you can make use of the features.

  15. In my opinion that a property foreclosures can have a significant effect on the debtor’s life. Mortgage foreclosures can have a 8 to 10 years negative impact on a debtor’s credit report. Any borrower who have applied for a mortgage or any kind of loans for example, knows that a worse credit rating will be, the more difficult it is to get a decent financial loan. In addition, it could possibly affect a new borrower’s capability to find a quality place to lease or hire, if that gets the alternative property solution. Thanks for your blog post.

  16. I have witnessed that intelligent real estate agents everywhere are Advertising. They are noticing that it’s in addition to placing a sign in the front area. It’s really about building relationships with these retailers who sooner or later will become customers. So, when you give your time and efforts to supporting these sellers go it alone : the “Law associated with Reciprocity” kicks in. Good blog post.

  17. Thanks, I have been looking for details about this subject matter for ages and yours is the best I’ve located so far.

  18. Hi, I think your site might be having browser compatibility issues. When I look at your blog site in Ie, 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, superb blog!

  19. Thanks for your posting on the vacation industry. I’d also like to add that if you are a senior thinking about traveling, it is absolutely imperative that you buy travel insurance for senior citizens. When traveling, senior citizens are at greatest risk being in need of a health emergency. Obtaining right insurance plan package for one’s age group can protect your health and provide you with peace of mind.

  20. I’ve learned some new things from your blog post. One other thing to I have found is that usually, FSBO sellers will probably reject you actually. Remember, they can prefer not to use your providers. But if you maintain a gentle, professional romance, offering guide and keeping contact for about four to five weeks, you will usually be capable of win interviews. From there, a house listing follows. Cheers

  21. Fantastic website. A lot of useful info here. I?m sending it to several friends ans also sharing in delicious. And of course, thanks for your sweat!

  22. Hi, Neat post. There’s a problem with your website in web explorer, may test this? IE nonetheless is the marketplace chief and a good section of other people will leave out your great writing because of this problem.

  23. It?s really a nice and helpful piece of info. I?m glad that you shared this useful info with us. Please keep us informed like this. Thanks for sharing.

  24. Thanks for helping me to get new strategies about desktops. I also have the belief that certain of the best ways to keep your notebook computer in leading condition is by using a hard plastic case, or maybe shell, that suits over the top of your computer. A lot of these protective gear are model specific since they are manufactured to fit perfectly within the natural casing. You can buy these directly from owner, or through third party places if they are available for your laptop, however not all laptop could have a covering on the market. Once again, thanks for your suggestions.

  25. I think this is among the most significant info for me. And i’m glad reading your article. But should remark on some general things, The site style is wonderful, the articles is really excellent : D. Good job, cheers

  26. Thanks for your recommendations on this blog. One thing I would choose to say is the fact that purchasing electronics items through the Internet is nothing new. The truth is, in the past decades alone, the marketplace for online consumer electronics has grown drastically. Today, you can get practically virtually any electronic system and devices on the Internet, which include cameras in addition to camcorders to computer elements and video games consoles.

  27. Magnificent site. A lot of useful info here. I?m sending it to a few friends ans additionally sharing in delicious. And naturally, thanks in your effort!

  28. Wonderful website you have here but I was curious if you knew of any community forums that cover the same topics discussed in this article? I’d really like to be a part of community where I can get comments from other knowledgeable people that share the same interest. If you have any suggestions, please let me know. Thank you!

發佈留言

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