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

20,152 Responses

  1. In the jap a part of the franchise, Farmers and Millers Bank in Milwaukee opened its doorways in 1853, growing into the primary Nationwide Financial institution of Milwaukee and finally changing into First Wisconsin and finally Firstar Corporation.

  2. Years later, the automotive was renamed the Dodge Charger Super Bee with a couple of the accessible colors being Stinger Yellow and Pitch Black.

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

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

  5. The primary-spherical action kicks off on Friday, 6 November with stay coverage from some of the anticipated ties on BBC Two at 19:30 GMT, offered by Dan Walker together with Trevor Sinclair and Jermaine Jenas.

  6. Cambridge financial handbooks. Vol.

  7. Since they develop at a speedy speed, they carry extra risk than fastened earnings cash.

  8. The borrower benefits if the interest charge falls however loses if the interest price increases.

  9. It ran 19 nights, that includes seven haunted houses.

  10. Well-outlined, properly-understood markets are merely more durable to master.

  11. That’s the one fragile exterior part on it, however you get colors and contrast that punches method above what most rivals can offer.

  12. This post has ᠎be​en g᠎enerat ed ᠎by GSA Con᠎tent Generator DE​MO.

  13. EU and Andorra signed a financial agreement on 30 June 2011 which made the euro the official forex in Andorra and allowed them to mint their very own euro coins as early as 1 July 2013, provided they comply with the settlement’s terms.

  14. вывод из запоя цены на дому краснодар вывод из запоя цены на дому краснодар .

  15. F*ckin? awesome issues here. I?m very happy to look your post. Thank you a lot and i am having a look forward to touch you. Will you kindly drop me a e-mail?

  16. DanielAbice表示:

    http://clomidonpharm.com/# how to get clomid

  17. I?ve been exploring for a bit for any high-quality articles or blog posts on this sort of area . Exploring in Yahoo I eventually stumbled upon this site. Reading this info So i?m satisfied to exhibit that I’ve a very good uncanny feeling I found out exactly what I needed. I most no doubt will make certain to don?t omit this site and provides it a glance regularly.

  18. SamuelBix表示:

    can you buy generic clomid without insurance: clomid on pharm – cost cheap clomid without dr prescription

  19. She’s a very gifted songwriter with an ideal ear for harmonies, and we spent much of that year writing songs, both alone and collectively.

  20. истинный запой [url=ekonomimvmeste.ukrbb.net/viewtopic.php?f=14&t=65423]истинный запой[/url] .

  21. Profession Growth and Growth: Amazon has assets for employee skill development, and there could also be alternatives for growth and development within the corporate.

  22. Valuable info. Lucky me I discovered your web site by chance, and I am surprised why this twist of fate didn’t took place earlier! I bookmarked it.

  23. Hi, I think your site 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, terrific blog!

  24. Mostbet PL表示:

    Oh my goodness! an amazing article dude. Thank you Nonetheless I’m experiencing concern with ur rss . Don?t know why Unable to subscribe to it. Is there anybody getting equivalent rss downside? Anybody who knows kindly respond. Thnkx

  25. Mostbet PL表示:

    I’m in awe of the author’s talent to make intricate concepts understandable to readers of all backgrounds. This article is a testament to his expertise and commitment to providing helpful insights. Thank you, author, for creating such an engaging and enlightening piece. It has been an unforgettable experience to read!

  26. Howdy just wanted to give you a quick heads up and let you know a few of the images aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different web browsers and both show the same outcome.

  27. вывод из запоя краснодар наркология вывод из запоя краснодар наркология .

發佈留言

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