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

  1. We absolutely love your blog and find almost all of your post’s to be just what I’m looking for. Would you offer guest writers to write content to suit your needs? I wouldn’t mind writing a post or elaborating on a few of the subjects you write related to here. Again, awesome web log!

  2. We absolutely love your blog and find most of your post’s to be just what I’m looking for. can you offer guest writers to write content in your case? I wouldn’t mind composing a post or elaborating on some of the subjects you write in relation to here. Again, awesome weblog!

  3. Also I believe that mesothelioma cancer is a uncommon form of many forms of cancer that is normally found in all those previously exposed to asbestos. Cancerous cells form from the mesothelium, which is a protective lining which covers many of the body’s bodily organs. These cells ordinarily form inside lining of the lungs, abdomen, or the sac which actually encircles the heart. Thanks for revealing your ideas.

  4. Hello there, simply became aware of your blog through Google, and found that it is truly informative. I?m gonna watch out for brussels. I?ll be grateful if you happen to proceed this in future. A lot of folks can be benefited from your writing. Cheers!

  5. We stumbled over here different web address and thought I might as well check things out. I like what I see so now i’m following you. Look forward to looking into your web page repeatedly.

  6. I have recently started a blog, the info you provide on this website has helped me greatly. Thanks for all of your time & work.

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

  8. I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to construct my own blog and would like to know where u got this from. thanks

  9. Oh my goodness! an amazing article dude. Thank you Nevertheless I am experiencing difficulty with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting similar rss problem? Anyone who knows kindly respond. Thnkx

  10. Hello, i believe that i saw you visited my website thus i came to ?return the desire?.I’m attempting to to find issues to improve my site!I suppose its ok to make use of a few of your concepts!!

  11. Nice blog right here! Also your site so much up very fast! What host are you the usage of? Can I get your associate link on your host? I want my website loaded up as fast as yours lol

  12. Hey there, I think your blog might be having browser compatibility issues. When I look at your blog site in Firefox, 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!

  13. Oh my goodness! an incredible article dude. Thanks Nonetheless I am experiencing problem with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting identical rss drawback? Anyone who is aware of kindly respond. Thnkx

  14. I would also like to add that if you do not surely have an insurance policy or perhaps you do not participate in any group insurance, you could well make use of seeking aid from a health agent. Self-employed or individuals with medical conditions usually seek the help of a health insurance specialist. Thanks for your text.

  15. I’m not that much of a online reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your site to come back later. Cheers

  16. An added important aspect is that if you are a senior citizen, travel insurance intended for pensioners is something you should really look at. The more mature you are, the more at risk you are for having something terrible happen to you while abroad. If you are definitely not covered by a few comprehensive insurance policy, you could have a number of serious complications. Thanks for giving your hints on this website.

  17. Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! By the way, how could we communicate?

  18. Pretty section of content. I just stumbled upon your website and in accession capital to assert that I get actually enjoyed account your blog posts. Any way I?ll be subscribing to your feeds and even I achievement you access consistently quickly.

  19. Treftis表示:

    Здравствуйте!
    Можно ли быстро купить диплом старого образца и в чем подвох?
    magadan-mebel.ru/forum/user/1011
    Поможем вам всегда!.

  20. Diplomi_mcEa表示:

    Привет, друзья!
    Купить документ университета можно в нашей компании в Москве.
    b24activities.ru/club/forum/messages/forum4/topic76/message147/?result=reply#message147

  21. Sazrtkf表示:

    Здравствуйте!
    Диплом для вас
    telegra.ph/kakiedokumentynuzhnydlyapostupleniyavvuzposlekolledzha0724

  22. Bianca表示:

    my web page – Bianca

  23. Mazrwfl表示:

    Привет, друзья!
    Аттестат школы купить официально с упрощенным обучением в Москве
    theafterlife.ru/zaklinanie-eb-dushi-serdca-egipetskaya-kniga-mertvyx

  24. вывод из запоя в стационаре краснодара вывод из запоя в стационаре краснодара .

  25. вывод из запоя круглосуточно https://www.vyvod-iz-zapoya-krasnodar12.ru .

  26. вывод из запоя в стационаре воронежа http://www.vyvod-iz-zapoya-v-stacionare-voronezh11.ru .

  27. Sazrhjw表示:

    Здравствуйте!
    Мы предлагаем дипломы любой профессии.
    Покупка диплома, подтверждающего окончание института, – это грамотное решение.
    lada-xray.net/member.php?tab=visitor_messaging&u=2434&page=3
    Рады оказать помощь!.

  28. What?s Happening i am new to this, I stumbled upon this I’ve found It positively helpful and it has aided me out loads. I hope to contribute & aid other users like its aided me. Great job.

  29. Thanks for the good writeup. It if truth be told was once a amusement account it. Look complex to more brought agreeable from you! By the way, how can we keep up a correspondence?

發佈留言

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