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

27,891 Responses

  1. Traders must make an preliminary deposit that gets settled by a clearinghouse earlier than buying and selling in these devices.

  2. I don?t even know the way I finished up here, but I thought this post used to be great. I don’t recognize who you are however certainly you are going to a famous blogger if you happen to aren’t already 😉 Cheers!

  3. By following the following pointers, you may take pleasure in the advantages of your jade crystal for years to come.

  4. Briantrozy表示:

    zithromax 250 mg australia: zithromax cost australia – can you buy zithromax online

  5. Briantrozy表示:

    amoxicillin 825 mg: amoxicillin 500 mg online – amoxicillin generic brand

  6. The rental property company may be very profitable however consists of a fair quantity of danger.

  7. A different issue is really that video gaming has become one of the all-time largest forms of excitement for people spanning various ages. Kids engage in video games, plus adults do, too. Your XBox 360 is amongst the favorite video games systems for those who love to have hundreds of video games available to them, and who like to relax and play live with other people all over the world. Thank you for sharing your notions.

  8. I do agree with all of the ideas you have presented in your post. They’re really convincing and will certainly work. Still, the posts are too short for novices. Could you please extend them a bit from next time? Thanks for the post.

  9. Briantrozy表示:

    amoxicillin order online: Amo Health Pharm – amoxicillin 875 mg tablet

  10. If more individuals started utilizing them, it might have a optimistic influence on the surroundings and society.

  11. Roberttic表示:

    https://zithropharm.com/# zithromax for sale cheap

  12. Roberttic表示:

    https://clmhealthpharm.com/# get cheap clomid without rx

  13. BrandonJag表示:

    buy zithromax no prescription: zithromax for sale usa – buy zithromax 1000 mg online

  14. JustinTam表示:

    over the counter amoxicillin: can you purchase amoxicillin online – amoxicillin 500mg capsules uk

  15. mddqjyyqr表示:

    @rbsace I gotta say that I didn’t wanna buy the game (heard it was TERRIBLY rushed, barely put together AND would probably run horrible on my potato of a i-5…). I did try to watch a little on ewetoob… Wasn’t really impressed, tho still a big fan of Keanu, just in other stuff. Balloon Blast: Pop Puzzle Game El Capcom Play System 2 (CPS-2), introducido por Capcom en 1993, fue la evolución de la placa del sistema arcade CPS-1 original. Con una capacidad gráfica y de sonido significativamente mejorada, el CPS-2 permitió a los desarrolladores utilizar sprites más detallados, animaciones más fluidas y efectos de audio de mayor calidad. Esto dio lugar a algunos de los títulos más destacados de esta plataforma, como Super Street Fighter II, la serie Street Fighter Alpha, la serie Darkstalkers y crossovers como X-Men vs. Street.
    https://fiorepr.com/2025/02/14/descarga-smartsoft-gaming-balloon-apk-desplazandolo-hacia-el-pelo-percibe-la-conmocion-falto-limites/
    Putt-Putt® and Pep’s Balloon-o-Rama ©2019 Tommo Inc. All rights reserved. This Product and Humongous Entertainment are not in any manner affiliated with Putt-Putt, LLC. The PUTT-PUTT® trademark is a registered trademark of Putt-Putt, LLC and is used under license.Humongous Entertainment and the Humongous Entertainment logo are trademarks or registered trademarks of Tommo Inc. All other trademarks are the property of their respective owners. Hay un problema al recuperar su cesta en este momento __name_short_html__ The Humongous Entertainment Complete Pack gives you instant access to all 35 games from the following bundles. Putt-Putt Complete Pack Pajama Sam Complete PackFreddi Fish Complete PackSpy Fox Complete PackJunior Field Trip Complete PackBig Thinkers! 1st GradeBig Thinkers KindergartenFatty Bear’s Birthday Surprise

  16. Briantrozy表示:

    zithromax price south africa: Zithro Pharm – buy zithromax online

  17. JustinTam表示:

    generic zithromax over the counter: Zithro Pharm – zithromax 500 price

  18. JustinTam表示:

    amoxicillin 500 mg purchase without prescription: AmoHealthPharm – where can i buy amoxicillin over the counter uk

  19. Thanks for your publication on the vacation industry. I’d personally also like contribute that if you are one senior taking into account traveling, it can be absolutely essential that you buy travel cover for seniors. When traveling, senior citizens are at greatest risk being in need of a health emergency. Receiving the right insurance plan package in your age group can safeguard your health and give you peace of mind.

  20. Roberttic表示:

    https://amohealthpharm.shop/# where can i buy amoxicillin without prec

  21. Roberttic表示:

    https://clmhealthpharm.com/# can i buy cheap clomid without prescription

  22. JustinTam表示:

    purchase amoxicillin 500 mg: amoxicillin cost australia – amoxicillin capsules 250mg

  23. BrandonJag表示:

    amoxicillin from canada: how much is amoxicillin – generic amoxicillin

  24. BrandonJag表示:

    buy zithromax online: zithromax pill – zithromax cost uk

  25. JustinTam表示:

    zithromax 500: zithromax online usa no prescription – generic zithromax online paypal

  26. BrandonJag表示:

    zithromax prescription: zithromax without prescription – can i buy zithromax over the counter in canada

  27. VirgilBlawl表示:

    doxycycline 50 mg price australia doxycycline canadian pharmacy doxycycline antibiotic

  28. Briantrozy表示:

    doxycycline 163: DoxHealthPharm – doxycycline south africa

發佈留言

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