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

35,101 Responses

  1. Derekgroum表示:

    Kamagra Original: Kamagra online bestellen – Kamagra Gel

  2. Malcolmseern表示:

    Kamagra online bestellen Kamagra Oral Jelly kaufen Kamagra online bestellen

  3. 늑대닷컴表示:

    Thanks for your submission. Another item is that to be a photographer entails not only problems in catching award-winning photographs but hardships in acquiring the best digital camera suited to your requirements and most especially issues in maintaining the grade of your camera. This is very correct and obvious for those professional photographers that are into capturing the nature’s exciting scenes – the mountains, the particular forests, the actual wild or perhaps the seas. Visiting these amazing places surely requires a digital camera that can surpass the wild’s severe areas.

  4. 늑대닷컴表示:

    One other thing is that an online business administration program is designed for students to be able to smoothly proceed to bachelors degree courses. The Ninety credit education meets the other bachelor diploma requirements when you earn your current associate of arts in BA online, you will have access to the latest technologies with this field. Some reasons why students want to be able to get their associate degree in business is because they’re interested in the field and want to obtain the general education necessary previous to jumping right into a bachelor education program. Thx for the tips you provide as part of your blog.

  5. Michaeltor表示:

    online apotheek: ApotheekMax – Beste online drogist

  6. 늑대닷컴表示:

    I was just searching for this information for some time. After 6 hours of continuous Googleing, finally I got it in your site. I wonder what’s the lack of Google strategy that don’t rank this type of informative websites in top of the list. Usually the top web sites are full of garbage.

  7. HarryRacle表示:

    подробнее здесь https://obnal-futbolka.ru

  8. For newest news you have to go to see web and on internet I
    found this site as a finest web site for most recent updates.

  9. Malcolmseern表示:

    apotek online apotek online Apoteket online

  10. Derekgroum表示:

    Kamagra Oral Jelly: Kamagra Original – Kamagra kaufen ohne Rezept

  11. Louislen表示:

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

  12. Derekgroum表示:

    Kamagra kaufen: Kamagra online bestellen – kamagra

  13. HarryRacle表示:

    нажмите здесь https://skam-futbolka.ru

  14. 늑대닷컴表示:

    Thanks for the tips about credit repair on this web-site. Things i would tell people should be to give up the actual mentality that they may buy now and pay back later. As a society we tend to try this for many things. This includes getaways, furniture, and also items we really want to have. However, you have to separate one’s wants from the needs. As long as you’re working to improve your credit rating score make some trade-offs. For example you may shop online to save money or you can go to second hand shops instead of pricey department stores pertaining to clothing.

  15. JeffreyDaymn表示:

    continue reading this
    russian ladies

  16. Michaeltor表示:

    Apotheek online bestellen: Beste online drogist – Apotheek Max

  17. 늑대닷컴表示:

    You can definitely see your enthusiasm in the paintings you write. The sector hopes for more passionate writers such as you who aren’t afraid to mention how they believe. At all times go after your heart.

  18. Michaeltor表示:

    Betrouwbare online apotheek zonder recept: Apotheek online bestellen – Betrouwbare online apotheek zonder recept

  19. HomerFaw表示:

    https://apotheekmax.shop/# Beste online drogist

  20. Derekgroum表示:

    de online drogist kortingscode: online apotheek – online apotheek

  21. 늑대닷컴表示:

    Thank you for this article. I would also like to talk about the fact that it can possibly be hard if you find yourself in school and just starting out to create a long credit ranking. There are many students who are only trying to survive and have a good or favourable credit history can sometimes be a difficult matter to have.

發佈回覆給「HomerFaw」的留言 取消回覆

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