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...

11,138 Responses

  1. Stephenzek表示:

    https://tamoxifen.bid/# nolvadex during cycle

  2. Another thing is that when evaluating a good on the web electronics store, look for web stores that are constantly updated, always keeping up-to-date with the latest products, the best deals, in addition to helpful information on products and services. This will ensure that you are dealing with a shop which stays atop the competition and provide you things to make educated, well-informed electronics purchases. Thanks for the crucial tips I have really learned from your blog.

  3. I can’t express how much I appreciate the effort the author has put into producing this outstanding piece of content. The clarity of the writing, the depth of analysis, and the wealth of information presented are simply impressive. Her zeal for the subject is apparent, and it has definitely made an impact with me. Thank you, author, for sharing your insights and enriching our lives with this extraordinary article!

  4. I do accept as true with all the ideas you’ve presented in your post. They’re very convincing and will certainly work. Still, the posts are too quick for novices. May you please extend them a bit from next time? Thank you for the post.

  5. Thanks for your submission. I also believe that laptop computers are becoming more and more popular currently, and now are sometimes the only form of computer found in a household. It is because at the same time that they are becoming more and more economical, their working power is growing to the point where these are as strong as pc’s from just a few in years past.

  6. Thanks , I have just been looking for information about this subject for ages and yours is the greatest I have discovered till now. But, what about the bottom line? Are you sure about the source?

  7. Whats up! I just would like to give an enormous thumbs up for the good information you have here on this post. I can be coming back to your weblog for extra soon.

  8. DanielTet表示:

    buy cytotec in usa http://tamoxifen.bid/# tamoxifen for sale
    furosemide

  9. I have been exploring for a little bit for any high quality articles or blog posts on this sort of area . Exploring in Yahoo I ultimately stumbled upon this web site. Reading this info So i?m happy to express that I have an incredibly good uncanny feeling I discovered exactly what I needed. I such a lot for sure will make certain to do not disregard this site and provides it a look regularly.

  10. I?d must check with you here. Which isn’t one thing I usually do! I enjoy reading a post that may make folks think. Additionally, thanks for allowing me to remark!

  11. Hey! This is my first visit to your blog! We are a team of volunteers and starting a new project in a community in the same niche. Your blog provided us beneficial information to work on. You have done a wonderful job!

  12. I really appreciate this post. I have been looking everywhere for this! Thank goodness I found it on Bing. You have made my day! Thanks again

  13. Great write-up, I?m regular visitor of one?s website, maintain up the excellent operate, and It is going to be a regular visitor for a long time.

  14. Thanks for your post. I’d like to write my opinion that the tariff of car insurance varies widely from one plan to another, simply because there are so many different facets which bring about the overall cost. As an example, the model and make of the vehicle will have a tremendous bearing on the price. A reliable older family vehicle will have a more economical premium than just a flashy performance car.

  15. Have you ever considered creating an e-book or guest authoring on other sites? I have a blog based on the same information you discuss and would love to have you share some stories/information. I know my visitors would enjoy your work. If you’re even remotely interested, feel free to shoot me an e-mail.

  16. Mazrhro表示:

    Привет!
    Быстрая покупка диплома старого образца: возможные риски
    furlib.ru/books/item/f00/s00/z0000008/st004.shtml

  17. I’ve been surfing on-line more than three hours these days, but I never discovered any fascinating article like yours. It?s beautiful worth sufficient for me. In my opinion, if all website owners and bloggers made good content material as you did, the web might be a lot more useful than ever before.

  18. It?s arduous to seek out educated people on this matter, but you sound like you already know what you?re talking about! Thanks

  19. Hello There. I found your blog using msn. This is a very well written article. I?ll be sure to bookmark it and come back to read more of your useful info. Thanks for the post. I?ll certainly return.

  20. One more thing. I believe that there are numerous travel insurance web pages of reputable companies that allow you enter a trip details to get you the insurance quotes. You can also purchase the actual international travel insurance policy online by using your credit card. All you should do will be to enter your own travel information and you can understand the plans side-by-side. Only find the program that suits your allowance and needs after which it use your bank credit card to buy that. Travel insurance on the web is a good way to check for a reliable company with regard to international travel insurance. Thanks for sharing your ideas.

  21. I really like what you guys are usually up too. Such clever work and exposure! Keep up the wonderful works guys I’ve incorporated you guys to my own blogroll.

  22. DanielTet表示:

    buy cytotec pills online cheap https://cytotec.pro/# buy cytotec pills online cheap
    lasix side effects

  23. Stanleyinolf表示:

    lisinopril capsule buy lisinopril online india lisinopril medicine

  24. Dnrthps表示:

    Привет, друзья!
    Заказать документ ВУЗа можно у нас.
    ba.rolka.me/viewtopic.php?id=15483#p18803

  25. Dnrthbe表示:

    Добрый день!
    Приобрести документ о получении высшего образования вы можете у нас в Москве.
    bestallorder.nethouse.ru/articles/gde-kupit-diplom-v-moskve

  26. Lazrpxl表示:

    Привет, друзья!
    Приобрести диплом университета.
    yuzhnoukrainsk.pogovorim.su/viewtopic.php?id=10970#p29127

發佈留言

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