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

  1. Hello! Do you know if they make any plugins to assist with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains. If you know of any please share. Many thanks!

  2. F*ckin? remarkable issues here. I?m very satisfied to look your article. Thank you so much and i’m looking ahead to contact you. Will you please drop me a e-mail?

  3. Thca Flower表示:

    Hello there, simply become alert to your weblog through Google, and located that it’s truly informative. I am going to watch out for brussels. I will appreciate if you happen to continue this in future. Many other folks might be benefited out of your writing. Cheers!

  4. Michaelchace表示:

    The world’s most liveable cities for 2024
    гей секс порно

    It’s considered among the most beautiful cities in the world to visit, and it seems that Vienna may also be an unbeatable place to live.

    The Austrian city has been crowned the most liveable city in the world yet again in the annual list from the Economist Intelligence Unit (EIU), which was released today.

    The EIU, a sister organization to The Economist, ranked 173 cities across the globe on a number of significant factors, including health care, culture and environment, stability, infrastructure and education.

    Vienna topped the list for the third consecutive year, receiving “perfect” scores in four out of five of the categories — the city was marked lower for culture and environment due to an apparent lack of significant sporting events.
    Just behind the Austrian capital, Denmark’s Copenhagen retained its second place position, while Switzerland’s Zurich moved up from sixth place to third on the list.

    Australia’s Melbourne fell from third to fourth place, while Canadian city Calgary tied for fifth place with Swiss city Geneva.

    Canada’s Vancouver and Australia’s Sydney were in joint seventh place, and Japan’s Osaka and New Zealand’s Auckland rounded out the top 10 in joint ninth place.

  5. Thca Flower表示:

    Thanks for expressing your ideas in this article. The other matter is that any time a problem comes up with a computer system motherboard, people today should not consider the risk regarding repairing that themselves for if it is not done correctly it can lead to permanent damage to the entire laptop. Most commonly it is safe just to approach the dealer of your laptop for any repair of the motherboard. They’ve already technicians who’ve an expertise in dealing with pc motherboard issues and can make right analysis and accomplish repairs.

  6. Thca Flower表示:

    Howdy! I’m at work surfing around your blog from my new apple iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the outstanding work!

  7. Thca Flower表示:

    My partner and I absolutely love your blog and find many of your post’s to be what precisely I’m looking for. can you offer guest writers to write content for yourself? I wouldn’t mind writing a post or elaborating on most of the subjects you write concerning here. Again, awesome website!

  8. Its like you learn my mind! You appear to grasp so much about this, such as you wrote the guide in it or something. I believe that you can do with a few p.c. to power the message home a little bit, but instead of that, this is wonderful blog. A fantastic read. I’ll certainly be back.

  9. Casa de apostas com pagamentos rapidos Blaze

  10. Thca Flower表示:

    Wonderful beat ! I wish to apprentice while you amend your site, how could i subscribe for a blog site? The account helped me a acceptable deal. I had been tiny bit acquainted of this your broadcast provided bright clear concept

  11. Ganhe muito no melhor cassino Blaze

  12. One thing I have actually noticed is the fact there are plenty of misconceptions regarding the banks intentions any time talking about property foreclosures. One misconception in particular is that often the bank prefers to have your house. The lending company wants your hard earned cash, not your own home. They want the amount of money they lent you with interest. Steering clear of the bank will simply draw any foreclosed realization. Thanks for your publication.

  13. What?s Happening i’m new to this, I stumbled upon this I have found It absolutely useful and it has aided me out loads. I hope to contribute & assist other users like its helped me. Great job.

  14. Qcmcgp表示:

    purchase disopyramide phosphate without prescription – disopyramide phosphate cost thorazine 50 mg uk

  15. This web page is really a walk-via for the entire information you needed about this and didn?t know who to ask. Glimpse right here, and also you?ll positively discover it.

  16. Very nice post. I just stumbled upon your blog and wished to say that I have truly enjoyed browsing your blog posts. In any case I will be subscribing to your rss feed and I hope you write again very soon!

  17. of course like your website but you need to check the spelling on several of your posts. Several of them are rife with spelling problems and I find it very troublesome to tell the truth nevertheless I?ll surely come back again.

  18. Thanks for the thoughts you have discussed here. Also, I believe usually there are some factors which will keep your motor insurance premium decrease. One is, to take into consideration buying vehicles that are inside the good list of car insurance businesses. Cars that happen to be expensive will be more at risk of being snatched. Aside from that insurance coverage is also in line with the value of your automobile, so the higher priced it is, then the higher your premium you spend.

  19. This actually answered my drawback, thank you!

  20. O cassino que todos recomendam Blaze

  21. Experimente a sorte no cassino mais famoso Blaze

  22. bokep jilbab表示:

    After research a number of of the blog posts on your website now, and I actually like your method of blogging. I bookmarked it to my bookmark web site list and might be checking again soon. Pls take a look at my site as well and let me know what you think.

  23. pure cbd oil表示:

    One thing I’d really like to say is before getting more computer system memory, have a look at the machine into which it would be installed. When the machine is actually running Windows XP, for instance, the particular memory threshold is 3.25GB. Setting up more than this would basically constitute some sort of waste. Make sure that one’s motherboard can handle an upgrade amount, as well. Good blog post.

  24. Thanks for your post right here. One thing I’d like to say is most professional job areas consider the Bachelors Degree as the entry level requirement for an online course. Though Associate Diplomas are a great way to begin with, completing ones Bachelors uncovers many doorways to various employment goodies, there are numerous internet Bachelor Course Programs available by institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another issue is that many brick and mortar institutions provide Online variations of their degree programs but typically for a considerably higher cost than the firms that specialize in online college degree plans.

  25. I learned more new stuff on this weight-loss issue. Just one issue is a good nutrition is tremendously vital if dieting. A tremendous reduction in bad foods, sugary food items, fried foods, sweet foods, red meat, and white-colored flour products can be necessary. Having wastes parasites, and harmful toxins may prevent desired goals for fat loss. While selected drugs for the short term solve the condition, the nasty side effects are certainly not worth it, plus they never provide more than a short-term solution. It is a known undeniable fact that 95 of fad diet plans fail. Many thanks for sharing your opinions on this weblog.

  26. pure cbd oil表示:

    Hiya, I am really glad I have found this info. Nowadays bloggers publish just about gossips and web and this is actually irritating. A good web site with interesting content, this is what I need. Thank you for keeping this web site, I will be visiting it. Do you do newsletters? Can not find it.

  27. 匿名訪客表示:

    Активируйте дверь к лучшей версии себя – перейдите по линку на %D0%9E%D0%9F%D0%A1%D0%A3%D0%98%D0%9C%D0%9E%D0%9B%D0%9E%D0%93

  28. bokep jilbab表示:

    The next time I learn a blog, I hope that it doesnt disappoint me as a lot as this one. I mean, I do know it was my choice to read, however I truly thought youd have something attention-grabbing to say. All I hear is a bunch of whining about one thing that you could possibly fix in the event you werent too busy looking for attention.

  29. I was curious if you ever considered 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 one or 2 images. Maybe you could space it out better?

  30. cbd massage表示:

    The things i have seen in terms of computer system memory is the fact that there are technical specs such as SDRAM, DDR etc, that must fit in with the technical specs of the motherboard. If the computer’s motherboard is reasonably current and there are no os issues, replacing the memory literally normally takes under a couple of hours. It’s one of the easiest computer system upgrade treatments one can imagine. Thanks for discussing your ideas.

發佈留言

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