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

  1. Wow, amazing blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is excellent, let alone the content!

  2. You made some first rate factors there. I seemed on the web for the difficulty and located most individuals will associate with along with your website.

  3. idx 82924737表示:

    I’d personally also like to mention that most individuals who find themselves without health insurance are normally students, self-employed and those that are out of work. More than half from the uninsured are under the age of Thirty five. They do not really feel they are looking for health insurance since they’re young and also healthy. Its income is often spent on real estate, food, in addition to entertainment. Most people that do go to work either whole or part-time are not provided insurance by means of their work so they get along without due to the rising expense of health insurance in the country. Thanks for the ideas you talk about through this web site.

  4. Thanks for the several tips discussed on this weblog. I have noticed that many insurers offer customers generous reductions if they favor to insure a few cars together. A significant variety of households have several motor vehicles these days, especially those with elderly teenage children still dwelling at home, and the savings in policies can soon mount up. So it is a good idea to look for a great deal.

  5. That is because La Niña, a companion weather phenomenon to the better-identified El Niño, is answerable for bringing periodic drought conditions to the southwestern United States.

  6. Nonetheless, clarification was later made in the letters to editors column in the same newspaper that Sun Hung Kai Properties’ overall share of major residential sales when it comes to attributable value from January to July 2010 has been roughly 20 – a figure that has been largely stable over the previous couple of years.

  7. Hi are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you need any coding knowledge to make your own blog? Any help would be really appreciated!

  8. Euro coins from any member state may be freely used in any nation that has adopted the euro.

  9. Hello, I think your website might be having browser compatibility issues. When I look at your blog site 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, wonderful blog!

  10. 1970s. Over the past 30 years, analysis and improvement has fluctuated with federal government interest and tax incentives.

  11. 勇勇しい表示:

    In 2005, Danmarks Nationalbank issued the first in a series of five 10-krone commemorative coins with motifs from Hans Christian Andersen’s fairy tales.

  12. Thank you, I have just been searching for info about this topic for ages and yours is the greatest I’ve discovered so far. But, what about the bottom line? Are you sure about the source?

  13. This is really attention-grabbing, You are an excessively professional blogger. I have joined your feed and look forward to in search of more of your magnificent post. Also, I have shared your website in my social networks!

  14. Interesting post right here. One thing I would really like to say is always that most professional areas consider the Bachelor’s Degree just as the entry level requirement for an online degree. While Associate Qualifications are a great way to get started on, completing a person’s Bachelors uncovers many entrances to various employment goodies, there are numerous online Bachelor Course Programs available by institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another concern is that many brick and mortar institutions make available Online variants of their qualifications but generally for a significantly higher fee than the corporations that specialize in online higher education degree plans.

  15. WONDERFUL Post.thanks for share..more wait .. ?

  16. Hello, I think your blog might be having browser compatibility issues. When I look at your website in Opera, 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!

  17. Good article. It is quite unfortunate that over the last several years, the travel industry has had to take on terrorism, SARS, tsunamis, influenza, swine flu, as well as the first ever entire global economic downturn. Through all this the industry has really proven to be sturdy, resilient as well as dynamic, discovering new ways to deal with adversity. There are usually fresh troubles and opportunities to which the marketplace must once again adapt and act in response.

  18. Please let me know if you’re looking for a article author for your site. You have some really great posts and I believe I would be a good asset. If you ever want to take some of the load off, I’d love to write some content for your blog in exchange for a link back to mine. Please blast me an e-mail if interested. Many thanks!

  19. This is really fascinating, You’re an overly skilled blogger. I’ve joined your rss feed and stay up for in the hunt for more of your great post. Additionally, I have shared your web site in my social networks!

  20. We’re a group of volunteers and opening a new scheme in our community. Your web site offered us with valuable information to work on. You’ve done an impressive job and our entire community will be grateful to you.

  21. I was curious if you ever thought of changing the page layout of your site? 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 1 or 2 images. Maybe you could space it out better?

  22. An attention-grabbing discussion is price comment. I feel that it’s best to write more on this matter, it may not be a taboo subject but generally persons are not sufficient to speak on such topics. To the next. Cheers

  23. I’ve come across that right now, more and more people are attracted to video cameras and the issue of photography. However, being photographer, you have to first expend so much of your time deciding the exact model of camera to buy along with moving from store to store just so you could possibly buy the most inexpensive camera of the trademark you have decided to choose. But it does not end at this time there. You also have to take into account whether you can purchase a digital photographic camera extended warranty. Thx for the good suggestions I gathered from your weblog.

  24. I am curious to find out what blog system you happen to be utilizing? I’m having some small security problems with my latest blog and I would like to find something more risk-free. Do you have any solutions?

  25. Oh my goodness! an incredible article dude. Thanks However I’m experiencing difficulty with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting identical rss problem? Anybody who knows kindly respond. Thnkx

  26. This was in response to a request on 6 April from the Chinese search engine company Sohu that Google cease distributing its pinyin IME software because it allegedly copied parts from Sohu’s personal software.

  27. It’s the best time to make some plans for the future and it’s time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or advice. Maybe you can write next articles referring to this article. I want to read more things about it!

  28. I’m impressed by the quality of this content! The author has undoubtedly put a great amount of effort into researching and structuring the information. It’s inspiring to come across an article that not only provides helpful information but also keeps the readers hooked from start to finish. Kudos to him for creating such a masterpiece!

發佈留言

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