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,757 Responses

  1. Jacobbep表示:

    trouver un mГ©dicament en pharmacie http://pharmaciemeilleurprix.com/# pharmacie en ligne livraison europe

  2. 789bet表示:

    One other issue is when you are in a predicament where you do not possess a co-signer then you may actually want to try to make use of all of your financing options. You could find many grants or loans and other free college funding that will present you with funding to help with education expenses. Many thanks for the post.

  3. Jacobbep表示:

    trouver un mГ©dicament en pharmacie https://pharmaciemeilleurprix.shop/# п»їpharmacie en ligne france

  4. U888表示:

    Please let me know if you’re looking for a article writer for your weblog. You have some really great posts and I think I would be a good asset. If you ever want to take some of the load off, I’d really like to write some material for your blog in exchange for a link back to mine. Please blast me an email if interested. Regards!

  5. U888表示:

    I’ve been absent for some time, but now I remember why I used to love this website. Thank you, I?ll try and check back more often. How frequently you update your site?

  6. NorbertKep表示:

    п»їpharmacie en ligne france: acheter kamagra site fiable – Pharmacie Internationale en ligne

  7. WilsonVah表示:

    Pharmacie en ligne livraison Europe: cialis generique – pharmacie en ligne livraison europe

  8. WilsonVah表示:

    pharmacie en ligne france livraison belgique: pharmacie en ligne sans ordonnance – acheter mГ©dicament en ligne sans ordonnance

  9. U888表示:

    Attractive part of content. I just stumbled upon your weblog and in accession capital to say that I acquire in fact enjoyed account your blog posts. Anyway I will be subscribing to your augment and even I fulfillment you get entry to constantly quickly.

  10. WW88表示:

    Good post. I study one thing tougher on totally different blogs everyday. It is going to all the time be stimulating to learn content material from other writers and follow just a little one thing from their store. I?d favor to make use of some with the content on my blog whether you don?t mind. Natually I?ll provide you with a link on your internet blog. Thanks for sharing.

  11. DonaldWrake表示:

    Эта публикация погружает вас в мир увлекательных фактов и удивительных открытий. Мы расскажем о ключевых событиях, которые изменили ход истории, и приоткроем завесу над научными достижениями, которые вдохновили миллионы. Узнайте, чему может научить нас прошлое и как применить эти знания в будущем.
    Подробнее тут – https://kapelnica-ot-zapoya-krasnoyarsk55.ru/

  12. Perryzoozy表示:

    Viagra sans ordonnance 24h Amazon Viagra pharmacie Le gГ©nГ©rique de Viagra

  13. NorbertKep表示:

    pharmacie en ligne fiable: Cialis sans ordonnance 24h – pharmacie en ligne avec ordonnance

  14. Interested by money-out refinance, but unsure if it’s for you?

  15. 发言稿表示:

    Thanks for the article.Really thank you! Fantastic.

  16. Matthewtrurn表示:

    Introducing Velodrome Finance: Maximize Your Crypto Yields
    In the rapidly evolving world of decentralized finance (DeFi), Velodrome Finance emerges as a robust platform for enthusiasts looking to enhance their crypto yield returns. This guide will walk you through the essentials of Velodrome Finance and how you can benefit from its features.
    velodrome finance
    Why Choose Velodrome Finance?
    Velodrome Finance stands out as a comprehensive DeFi protocol designed specifically for liquidity providers. Its innovative approach focuses on maximizing rewards while maintaining efficient and secure trading mechanisms. Here’s why it’s capturing the attention of the DeFi community:

    Efficient Token Swaps: Velodrome offers seamless and cost-effective token swapping capabilities.
    Liquidity Pools: Participants can provide liquidity to various pools, optimizing their earning potential.
    Yield Optimization: With advanced strategies, Velodrome helps users achieve superior returns on their investments.
    Secure Protocol: Security is a top priority, and Velodrome utilizes cutting-edge technology to protect user assets.
    Getting Started with Velodrome
    Embarking on your journey with Velodrome Finance is straightforward. Here’s a step-by-step guide to help you dive into the platform:

    Create a Wallet: To engage with Velodrome, you first need a compatible crypto wallet.
    Connect Your Wallet: Visit and securely link your crypto wallet.
    Explore Liquidity Pools: Browse through available pools and decide where to allocate your assets for optimal returns.
    Stake and Earn: Once you’ve funded a pool, begin staking and watch your earnings grow as you benefit from trading fees and incentives.
    Community and Support
    Velodrome Finance boasts a vibrant community ready to assist users at any step. Whether you’re a seasoned DeFi user or a newcomer, you can find guidance and support from community forums and dedicated customer service.

    Conclusion
    With its focus on maximizing crypto yield, Velodrome Finance is a compelling choice for anyone looking to delve deeper into the DeFi space. From efficient token swaps to robust security measures, it offers a complete ecosystem for those eager to optimize their returns. Visit the official site and start your journey towards enhanced financial growth.

  17. Is it worth buying an MP3 player?

  18. WilsonVah表示:

    pharmacie en ligne france pas cher: pharmacie en ligne sans ordonnance – pharmacies en ligne certifiГ©es

  19. Jacobbep表示:

    acheter mГ©dicament en ligne sans ordonnance https://pharmaciemeilleurprix.shop/# pharmacie en ligne france fiable

  20. Like Fair Trade companies, you as an investor will need to check out the investment organizations to make sure they are doing what they claim and to review their returns.

  21. Jacobbep表示:

    pharmacie en ligne livraison europe http://tadalafilmeilleurprix.com/# pharmacie en ligne

  22. Naumovska, Ivana (18 February 2021).

  23. Perryzoozy表示:

    trouver un mГ©dicament en pharmacie pharmacie en ligne sans ordonnance Achat mГ©dicament en ligne fiable

  24. Richardprurf表示:

    http://viagrameilleurprix.com/# Viagra sans ordonnance pharmacie France
    pharmacie en ligne france livraison belgique

  25. About per week after taking office, he issued a memorandum that radically reorganized the council.

  26. WilsonVah表示:

    acheter mГ©dicament en ligne sans ordonnance: kamagra gel – pharmacie en ligne avec ordonnance

  27. NorbertKep表示:

    pharmacie en ligne france livraison internationale: kamagra oral jelly – vente de mГ©dicament en ligne

  28. Richardprurf表示:

    http://viagrameilleurprix.com/# Viagra 100 mg sans ordonnance
    pharmacie en ligne livraison europe

發佈留言

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