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

  1. I have noticed that credit repair activity must be conducted with tactics. If not, you will probably find yourself causing harm to your positioning. In order to grow into success fixing your credit score you have to take care that from this moment in time you pay all your monthly dues promptly prior to their scheduled date. It is really significant for the reason that by definitely not accomplishing this, all other methods that you will choose to adopt to improve your credit rating will not be useful. Thanks for giving your tips.

  2. One other issue is that if you are in a circumstance where you do not have a cosigner then you may really need to try to exhaust all of your federal funding options. You can find many awards and other scholarships and grants that will offer you funding that can help with school expenses. Thanks a lot for the post.

  3. Wow that was unusual. I just wrote an really long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say superb blog!

  4. The following time I read a blog, I hope that it doesnt disappoint me as much as this one. I mean, I do know it was my option to read, but I truly thought youd have one thing fascinating to say. All I hear is a bunch of whining about something that you could possibly fix for those who werent too busy looking for attention.

  5. Отличный сайт! Всем рекомендую!справочник

  6. TomasRop表示:

    farmacia online senza ricetta: Farmacia online piu conveniente – comprare farmaci online all’estero

  7. RandyLunda表示:

    migliori farmacie online 2024: Farmacia online piu conveniente – farmacie online sicure

  8. RandyLunda表示:

    farmacia online: Farmacie che vendono Cialis senza ricetta – farmacie online autorizzate elenco

  9. Mazroap表示:

    Добрый день!
    Полезные советы по покупке диплома о высшем образовании без риска
    rushkadiplomik.ru

  10. RandyLunda表示:

    п»їFarmacia online migliore: farmacia online – migliori farmacie online 2024

  11. TomasRop表示:

    cialis farmacia senza ricetta: viagra senza ricetta – alternativa al viagra senza ricetta in farmacia

  12. I was just seeking this information for a while. After 6 hours of continuous Googleing, finally I got it in your site. I wonder what’s the lack of Google strategy that do not rank this type of informative sites in top of the list. Normally the top web sites are full of garbage.

  13. hello!,I like your writing very much! share we communicate more about your article on AOL? I need a specialist on this area to solve my problem. Maybe that’s you! Looking forward to see you.

  14. Hello would you mind sharing which blog platform you’re working with? I’m planning to start my own blog soon but I’m having a tough time choosing between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something unique. P.S Sorry for being off-topic but I had to ask!

  15. You really make it seem so easy with your presentation but I find this matter to be actually something that I think I would never understand. It seems too complex and extremely broad for me. I am looking forward for your next post, I will try to get the hang of it!

  16. Whats up! I just want to give an enormous thumbs up for the great data you will have here on this post. I will be coming back to your blog for more soon.

  17. Excellent blog here! Also your web site loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my site loaded up as quickly as yours lol

  18. great points altogether, you just gained a new reader. What would you suggest about your post that you made a few days ago? Any positive?

  19. Valuable information. Lucky me I found your website by accident, and I’m shocked why this accident didn’t happened earlier! I bookmarked it.

  20. It?s really a nice and helpful piece of information. I am glad that you shared this useful info with us. Please keep us up to date like this. Thanks for sharing.

  21. I am really enjoying the theme/design of your weblog. Do you ever run into any browser compatibility problems? A couple of my blog readers have complained about my blog not operating correctly in Explorer but looks great in Chrome. Do you have any recommendations to help fix this issue?

  22. TomasRop表示:

    acquistare farmaci senza ricetta: Avanafil compresse – Farmacie online sicure

  23. twd ss9 ep6表示:

    Amazing! This blog looks just like my old one! It’s on a entirely different topic but it has pretty much the same layout and design. Superb choice of colors!

  24. Diplomi_lgEa表示:

    Привет!
    Приобрести документ о получении высшего образования можно в нашей компании.
    diploms-rushkas.ru

  25. I have seen a great deal of useful things on your web page about computer systems. However, I’ve got the viewpoint that notebooks are still not quite powerful adequately to be a sensible choice if you often do projects that require loads of power, like video enhancing. But for internet surfing, microsoft word processing, and the majority of other common computer work they are just great, provided you don’t mind the small screen size. Thank you for sharing your ideas.

  26. Hi there, You’ve performed an excellent job. I will definitely digg it and in my opinion recommend to my friends. I’m sure they will be benefited from this site.

  27. certainly like your website but you need to check the spelling on several of your posts. A number of them are rife with spelling issues and I find it very troublesome to tell the truth nevertheless I?ll certainly come back again.

  28. Hey there! Do you know if they make any plugins to help with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success. If you know of any please share. Thanks!

  29. What i do not understood is actually how you’re not really much more well-liked than you may be right now. You are very intelligent. You realize therefore considerably relating to this subject, produced me personally consider it from so many varied angles. Its like women and men aren’t fascinated unless it is one thing to accomplish with Lady gaga! Your own stuffs great. Always maintain it up!

  30. Have you ever thought about adding a little bit more than just your articles? I mean, what you say is important and everything. But imagine if you added some great pictures or videos to give your posts more, “pop”! Your content is excellent but with images and videos, this site could certainly be one of the best in its niche. Good blog!

發佈留言

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