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

34,985 Responses

  1. Derekgroum表示:

    apotek pa nett: Apotek hemleverans recept – apotek pa nett

  2. Greetings! I know this is somewhat off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one? Thanks a lot!

  3. Louislen表示:

    https://apotekonlinerecept.com/# apotek online recept

  4. Derekgroum表示:

    Kamagra Oral Jelly kaufen: Kamagra kaufen ohne Rezept – Kamagra kaufen ohne Rezept

  5. fantastic points altogether, you just received a brand new reader. What may you recommend about your submit that you simply made a few days in the past? Any positive?

  6. Louislen表示:

    http://apotekonlinerecept.com/# Apotek hemleverans recept

  7. Derekgroum表示:

    apotek online recept: apotek online recept – apotek pa nett

  8. HomerFaw表示:

    https://apotheekmax.com/# online apotheek

  9. Great blog article.Much thanks again. Much obliged.

  10. Michaeltor表示:

    Apotheek Max: Online apotheek Nederland met recept – Apotheek online bestellen

  11. Thank you a bunch for sharing this with all of us you really understand what you’re speaking approximately! Bookmarked. Kindly additionally discuss with my website =). We will have a link alternate agreement among us!

  12. Добро пожаловать на sofisimo.com, на sofisimo.com вас ждут.
    Погрузитесь в уникальный контент sofisimo.com, новые тренды.
    Сайт sofisimo.com – ваша отправная точка, находя.
    sofisimo.com – остров знаний, где.
    Узнайте, как sofisimo.com может помочь вам, находя новые знания.
    Общайтесь, учитесь и развивайтесь на sofisimo.com, вы можете.
    Платформа sofisimo.com наполнена вдохновением, инновации.
    Посетите sofisimo.com для открытия новых возможностей, исследуйте.
    Откройте для себя мир sofisimo.com, учиться.
    Погружение в sofisimo.com – ваш путь к успеху, профессионалы.
    Так много возможностей на sofisimo.com, что-то для себя.
    sofisimo.com – это ваш надежный партнер, учиться.
    sofisimo.com – свяжитесь с единомышленниками, что.
    sofisimo.com – ваша стартовая площадка, где каждый.
    sofisimo.com – навигатор в мире информации, для вашей карьеры.
    sofisimo.com – это не просто сайт, ключ к успеху для каждого.
    sofisimo.com ждет вас, ваши идеи будут иметь значение.
    Ищите новую информацию на sofisimo.com, вдохновение не заканчивается.
    sofisimo.com: место, где встречаются идеи, вы можете.
    camas y colchones https://sofisimo.com/ .

  13. Louislen表示:

    http://apotheekmax.com/# ApotheekMax

  14. Derekgroum表示:

    kamagra: kamagra – Kamagra kaufen

  15. Hiya, I am really glad I have found this information. Today bloggers publish just about gossips and web and this is really irritating. A good blog with interesting content, this is what I need. Thank you for keeping this web-site, I will be visiting it. Do you do newsletters? Can’t find it.

  16. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:сервисные центры в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  17. Malcolmseern表示:

    Online apotheek Nederland zonder recept online apotheek de online drogist kortingscode

  18. HomerFaw表示:

    https://kamagrapotenzmittel.shop/# Kamagra Oral Jelly

  19. We would also like to mention that most individuals that find themselves devoid of health insurance usually are students, self-employed and people who are unemployed. More than half of those uninsured are really under the age of 35. They do not experience they are needing health insurance because they are young plus healthy. Its income is frequently spent on housing, food, plus entertainment. Most people that do represent the working class either whole or part time are not provided insurance through their jobs so they get along without as a result of rising valuation on health insurance in the United States. Thanks for the ideas you write about through this site.

  20. gas mask表示:

    I am so grateful for your blog article.Really thank you! Want more.

  21. Great article. It is very unfortunate that over the last one decade, the travel industry has already been able to to tackle terrorism, SARS, tsunamis, bird flu virus, swine flu, as well as the first ever entire global economic downturn. Through it the industry has proven to be powerful, resilient in addition to dynamic, acquiring new ways to deal with hardship. There are often fresh problems and opportunity to which the business must again adapt and act in response.

  22. Louislen表示:

    https://kamagrapotenzmittel.com/# Kamagra Oral Jelly kaufen

  23. I?m impressed, I must say. Really hardly ever do I encounter a weblog that?s each educative and entertaining, and let me inform you, you’ve got hit the nail on the head. Your thought is outstanding; the difficulty is one thing that not enough individuals are speaking intelligently about. I’m very comfortable that I stumbled throughout this in my search for one thing relating to this.

  24. Michaeltor表示:

    online apotheek: Online apotheek Nederland met recept – Betrouwbare online apotheek zonder recept

  25. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:сервисные центры по ремонту техники в мск
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  26. I cherished up to you will obtain performed proper here. The comic strip is attractive, your authored subject matter stylish. nonetheless, you command get bought an shakiness over that you would like be handing over the following. in poor health unquestionably come further previously once more as precisely the similar just about a lot often inside case you shield this increase.

  27. Malcolmseern表示:

    Betrouwbare online apotheek zonder recept ApotheekMax Online apotheek Nederland zonder recept

  28. whoah this weblog is magnificent i love reading your articles. Keep up the good work! You realize, many people are looking round for this info, you could aid them greatly.

  29. Derekgroum表示:

    online apotheek: ApotheekMax – de online drogist kortingscode

發佈回覆給「カジノゲーム紹介」的留言 取消回覆

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