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

  1. One thing I would like to say is the fact before acquiring more laptop or computer memory, look at the machine directly into which it can be installed. Should the machine is running Windows XP, for instance, a memory ceiling is 3.25GB. Putting in in excess of this would basically constitute some sort of waste. Make sure one’s mother board can handle the particular upgrade amount, as well. Great blog post.

  2. Dino Game 119表示:

    I think this is among the most vital info for me. And i’m glad reading your article. But want to remark on some general things, The web site style is ideal, the articles is really nice : D. Good job, cheers

  3. DanielTet表示:

    buy misoprostol over the counter http://cytotec.pro/# cytotec buy online usa
    furosemida 40 mg

  4. Lazrkfh表示:

    Привет!
    Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по выгодным ценам.
    telegra.ph/obuchenie-v-vuzah-ssha-08-02

  5. Hello there, You have done an excellent job. I?ll definitely digg it and personally suggest to my friends. I am confident they will be benefited from this website.

  6. Dino Game 129表示:

    Thanks for every other wonderful post. Where else could anyone get that type of info in such an ideal way of writing? I have a presentation next week, and I’m at the look for such info.

  7. I think this is one of the most important information for me. And i am glad reading your article. But want to remark on some general things, The website style is perfect, the articles is really great : D. Good job, cheers

  8. Incredible! This blog looks exactly like my old one! It’s on a completely different subject but it has pretty much the same layout and design. Wonderful choice of colors!

  9. Dino Game 119表示:

    Thank you for another informative blog. Where else could I get that kind of info written in such an ideal way? I have a project that I am just now working on, and I’ve been on the look out for such info.

  10. Dino Game 120表示:

    Hiya, I am really glad I have found this info. Today bloggers publish just about gossips and net and this is actually irritating. A good web site with interesting content, that’s what I need. Thanks for keeping this web-site, I’ll be visiting it. Do you do newsletters? Cant find it.

  11. Dino Game 119表示:

    Valuable information. Fortunate me I found your site by chance, and I’m shocked why this accident didn’t came about in advance! I bookmarked it.

  12. Hello there! I could have sworn I’ve been to this website before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely delighted I found it and I’ll be bookmarking and checking back often!

  13. WONDERFUL Post.thanks for share..extra wait .. ?

  14. Thanks for your publication. One other thing is always that individual American states have their very own laws that affect property owners, which makes it very difficult for the the nation’s lawmakers to come up with a fresh set of guidelines concerning home foreclosure on people. The problem is that every state has own regulations which may have interaction in an adverse manner with regards to foreclosure plans.

  15. Stephenzek表示:

    https://cytotec.pro/# buy cytotec

  16. Stephenzek表示:

    https://tamoxifen.bid/# tamoxifen skin changes

  17. Dino Game 125表示:

    Hey there, You have performed an incredible job. I will definitely digg it and for my part recommend to my friends. I’m sure they will be benefited from this site.

  18. Kolyaski_ceSa表示:

    Идеальные коляски для прогулок с погодкой, доставят комфорт и удовольствие.
    Экспертные советы по выбору коляски для погодки, и удовлетворит все потребности вашего питомца.
    Самые популярные коляски для погодок этого сезона, гарантируют безопасность и комфорт вашей погодке.
    Как правильно ухаживать за коляской погодки, продлить срок службы вашей коляски.
    Стильные аксессуары для колясок погодок, добавят шарма и стиля вашей коляске.
    Уникальные возможности колясок для погодок, и незаменимыми для настоящих ценителей удобства.
    Какие коляски для погодок выбирают знаменитости, чтобы и ваша погодка могла чувствовать себя звездой.
    Какая коляска для погодки подойдет вашему питомцу, которая станет незаменимым аксессуаром для вашего питомца.
    Простые советы по организации прогулок для вашей погодки, и принесут не только удовольствие, но и пользу.
    Новинки в мире колясок для погодок, чтобы сделать прогулки с погодкой еще более приятными.
    Инновации в сфере колясок для погодок, для тех, кто ценит удобство и качество.
    5 причин выбрать именно коляску для погодки, для тех, кто ценит удобство и стиль.
    Секреты правильного выбора коляски для погодки, которая подчеркнет ваш стиль и индивидуальность.
    Эксклюзивные коляски для погодок, для тех, кто ценит комфорт и качество.
    Лучшие варианты колясок для вашей погодки, которые сделают ваши прогулки незабываемыми.
    Как подобрать идеальную коляску для погодки
    компактная коляска для погодок https://kolyaskidlyapogodok.ru/ .

  19. Jamesric表示:

    buy lisinopril 10 mg online: Lisinopril refill online – order lisinopril online us

  20. Music started playing as soon as I opened this blog, so annoying!

  21. Valuable information. Lucky me I found your web site by accident, and I’m shocked why this accident did not happened earlier! I bookmarked it.

  22. Hello There. I found your blog using msn. This is a really well written article. I?ll make sure to bookmark it and come back to read more of your useful information. Thanks for the post. I?ll definitely comeback.

  23. Live Poker表示:

    Feel free to surf to my web blog :: Live Poker

  24. Jamesric表示:

    can i buy lisinopril in mexico: website – price of lisinopril 20 mg

  25. Dino Game 120表示:

    Pretty section of content. I just stumbled upon your weblog and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently fast.

  26. Jamesric表示:

    buy cytotec over the counter: buy cytotec online – Abortion pills online

  27. Undeniably 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 annoyed while people consider worries that they plainly don’t know about. You managed to hit the nail upon the top and also defined out the whole thing without having side effect , people can take a signal. Will likely be back to get more. Thanks

  28. Thanks for your article. I have often seen that the majority of people are desirous to lose weight when they wish to look slim in addition to looking attractive. However, they do not continually realize that there are additional benefits to losing weight additionally. Doctors insist that overweight people come across a variety of diseases that can be perfectely attributed to their own excess weight. The great thing is that people who’re overweight plus suffering from several diseases are able to reduce the severity of their own illnesses by way of losing weight. It is easy to see a gradual but noted improvement with health when even a minor amount of fat loss is obtained.

  29. Dino Game 129表示:

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

  30. Dino Game 121表示:

    you are really a good webmaster. The site loading speed is amazing. It seems that you’re doing any unique trick. Moreover, The contents are masterpiece. you have done a wonderful job on this topic!

發佈留言

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