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

32,575 Responses

  1. Thank you for any other informative blog. The place else may I get that type of info written in such a perfect way? I’ve a venture that I’m just now running on, and I’ve been on the look out for such info.

  2. Hmm is anyone else encountering problems with the images on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog. Any feedback would be greatly appreciated.

  3. TerryDus表示:

    https://kamagrakopen.pro/# kamagra jelly kopen

  4. Very great post. I just stumbled upon your weblog and wanted to say that I have truly loved browsing your blog posts. In any case I will be subscribing in your feed and I hope you write once more soon!

  5. I know this if off topic but I’m looking into starting my own blog and was curious what all is needed to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet savvy so I’m not 100 positive. Any tips or advice would be greatly appreciated. Many thanks

  6. Thanks for your post on this web site. From my own experience, periodically softening up a photograph may possibly provide the photo shooter with a little bit of an inventive flare. Often times however, this soft cloud isn’t just what exactly you had as the primary goal and can usually spoil a normally good picture, especially if you thinking about enlarging that.

  7. I?ve read some good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to make such a excellent informative web site.

  8. Kennethslity表示:

    https://kamagrakopen.pro/# Kamagra Kopen

  9. raz vape表示:

    Hi there, simply became aware of your weblog via Google, and located that it is truly informative. I am going to be careful for brussels. I?ll appreciate in case you proceed this in future. Many people will likely be benefited from your writing. Cheers!

  10. I?ve read several good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to create such a excellent informative website.

  11. Dwayneseisa表示:

    Generic100mgEasy Generic 100mg Easy Viagra Tablet price

  12. One thing I would like to say is that car insurance cancellation is a terrifying experience and if you’re doing the correct things like a driver you’ll not get one. Lots of people do obtain the notice that they have been officially dumped by their own insurance company they have to struggle to get added insurance from a cancellation. Affordable auto insurance rates tend to be hard to get after having a cancellation. Understanding the main reasons concerning the auto insurance canceling can help drivers prevent getting rid of in one of the most critical privileges readily available. Thanks for the suggestions shared via your blog.

  13. Yet another thing I would like to state is that in place of trying to suit all your online degree courses on days that you end work (since the majority of people are tired when they go back home), try to have most of your classes on the saturdays and sundays and only 1 or 2 courses on weekdays, even if it means taking some time off your saturdays. This is fantastic because on the saturdays and sundays, you will be much more rested and concentrated for school work. Thanks a lot for the different suggestions I have acquired from your site.

  14. raz vape表示:

    magnificent points altogether, you just gained a new reader. What would you recommend in regards to your post that you made some days ago? Any positive?

  15. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your webpage? My blog is in the exact same niche as yours and my visitors would genuinely benefit from a lot of the information you provide here. Please let me know if this alright with you. Thank you!

  16. I have noticed that online degree is getting preferred because accomplishing your degree online has changed into a popular option for many people. Many people have definitely not had a possible opportunity to attend a regular college or university nevertheless seek the raised earning possibilities and a better job that a Bachelor Degree offers. Still some others might have a degree in one discipline but would like to pursue some thing they now possess an interest in.

  17. Sa Gaming表示:

    I was wondering if you ever thought of 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?

  18. raz vape表示:

    As I web-site possessor I believe the content material here is rattling magnificent , appreciate it for your efforts. You should keep it up forever! Good Luck.

  19. Williszew表示:

    https://indiamedfast.shop/# IndiaMedFast.com

  20. Arthurhow表示:

    https://interpharmonline.shop/# canadapharmacyonline com
    canada pharmacy online

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

  22. Thanks for the new stuff you have unveiled in your text. One thing I would really like to comment on is that FSBO connections are built after some time. By presenting yourself to the owners the first weekend their FSBO can be announced, ahead of the masses begin calling on Mon, you build a good network. By sending them instruments, educational components, free reviews, and forms, you become the ally. By using a personal curiosity about them and their scenario, you make a solid relationship that, on many occasions, pays off if the owners opt with a realtor they know and also trust — preferably you.

  23. whoah this blog is fantastic i love reading your posts. Keep up the great work! You know, a lot of people are looking around for this information, you can help them greatly.

  24. This is very interesting, You’re a very skilled blogger. I’ve joined your feed and look forward to seeking more of your wonderful post. Also, I have shared your web site in my social networks!

  25. As I website possessor I believe the content material here is rattling excellent , appreciate it for your efforts. You should keep it up forever! Best of luck.

  26. Howardenace表示:

    canadian pharmacy ltd: legitimate canadian pharmacies online – pharmacy rx world canada

  27. Montebeera表示:

    buying from canadian pharmacies most reliable canadian online pharmacies canadian pharmacy online store

  28. I loved as much as you will receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get bought an nervousness over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you shield this hike.

  29. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали срочный ремонт приставок xbox, можете посмотреть на сайте: ремонт приставок xbox рядом
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  30. Hey there! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My blog looks weird when browsing from my iphone. I’m trying to find a template or plugin that might be able to correct this problem. If you have any recommendations, please share. Appreciate it!

發佈留言

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