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

22,870 Responses

  1. OLaneevige表示:

    Hi I am so thrilled I found your website, I really found you by error, while I was researching on Askjeeve for something else, Regardless I am here now and would just like to say cheers for a incredible post and a all round interesting blog (I also love the theme/design), I don’t have time to browse it all at the minute but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the awesome work.

    https://direstrats.com/wp-includes/inc/1xbet_promo_code.html

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

  3. Check out my homepage online dating app for
    pc (community.discountasp.net)

  4. KennethPah表示:

    get cheap clomid for sale clomid on pharm where to get clomid without insurance

  5. I believe that avoiding refined foods is the first step so that you can lose weight. They will often taste very good, but highly processed foods have got very little nutritional value, making you take more just to have enough vitality to get over the day. Should you be constantly feeding on these foods, changing to whole grains and other complex carbohydrates will make you to have more energy while consuming less. Good blog post.

  6. Gregorysuify表示:

    The 1xBet promo code 2025: 1XNEW25. Use to register a new member, get a sports bonus 100% up to €130 and casino bonus €1950 + 150 free spins. Use the bonus code when registering and you are guaranteed to receive a 2025 welcome bonus from 1xBet. The 1xBet bookmaker has proven itself to be time-tested, it has high odds for sports betting, and a huge number of slots in the cauldron section, there are also roulette, poker, and fast online games like Aviator.

    https://sneakerlinks.com/wp-content/pages/?1xbet-promo-code_131.html – 1xbet new account promo code

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

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

  9. KennethPah表示:

    antibiotics cipro purchase cipro buy cipro online without prescription

  10. SamuelBix表示:

    amoxicillin medicine over the counter: amoxicillin where to get – buy cheap amoxicillin

  11. SamuelBix表示:

    buy ciprofloxacin over the counter: ci pharm delivery – cipro 500mg best prices

  12. DanielAbice表示:

    http://cipharmdelivery.com/# buy cipro no rx

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

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

  15. Greetings! I’ve been following your weblog for some time now and finally got the bravery to go ahead and give you a shout out from New Caney Texas! Just wanted to tell you keep up the good work!

  16. DanielAbice表示:

    http://prednibest.com/# prednisone 10 mg over the counter

  17. SamuelBix表示:

    where to get amoxicillin over the counter: amoxicillin medicine – generic amoxicillin

  18. RobertJar表示:

    can i order cheap clomid: can i order cheap clomid without rx – buy cheap clomid without dr prescription

  19. RobertJar表示:

    875 mg amoxicillin cost: buy amoxicillin 500mg uk – amoxicillin 500mg pill

  20. RobertJar表示:

    buy generic ciprofloxacin: buy cipro cheap – ciprofloxacin over the counter

  21. KennethPah表示:

    where can i buy clomid pills where buy generic clomid for sale order generic clomid tablets

  22. анонимный чат с девушками http://anonimnyj-chat11.ru .

  23. Liburan Mewah表示:

    Koko Traveling adalah sebuah portal berita yang berfokus pada informasi seputar liburan mewah. Portal ini menyediakan berbagai artikel inspiratif, panduan perjalanan, dan rekomendasi tempat liburan mewah di indonesia eksklusif yang cocok untuk wisatawan premium.

  24. анонимный чат знакомств анонимный чат знакомств .

  25. The “calvo” password is exclusive in that it is likely one of the few passwords in the game that can be guessed, quite than read out of a datacube (it appears on a poster in Alex’s office).

  26. There are several dance firms in Flagstaff, together with Coconino Group Faculty Dance Program, Northern Arizona Preparatory Firm and Canyon Movement, which present periodic concerts and collaborate with the Flagstaff Symphony without spending a dime concert events through the summer season and holiday seasons.

  27. никто чат [url=http://anonimnyj-chat11.ru]никто чат[/url] .

  28. The ship is the fifth extremely-luxurious vessel to join the Seabourn fleet over the past decade and the second of two ships designed by Adam D. Tihany.

  29. общение онлайн с людьми общение онлайн с людьми .

  30. Attractive section of content. I just stumbled upon your website and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I?ll be subscribing to your augment and even I achievement you access consistently rapidly.

發佈留言

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