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

32,218 Responses

  1. 누누티비表示:

    certainly like your website however you need to take a look at the spelling on quite a few of your posts. Many of them are rife with spelling problems and I find it very troublesome to inform the truth on the other hand I?ll definitely come back again.

  2. 누누티비表示:

    That is very interesting, You are an overly professional blogger. I’ve joined your feed and stay up for seeking extra of your magnificent post. Additionally, I’ve shared your site in my social networks!

  3. Arthurhow表示:

    https://interpharmonline.shop/# canadian pharmacy mall
    best rated canadian pharmacy

  4. 누누티비表示:

    Very great post. I simply stumbled upon your weblog and wished to mention that I’ve really loved surfing around your weblog posts. After all I will be subscribing to your rss feed and I am hoping you write again very soon!

  5. 누누티비表示:

    Hello! This post couldn’t be written any better! Reading this post reminds me of my good old room mate! He always kept talking about this. I will forward this page to him. Fairly certain he will have a good read. Thanks for sharing!

  6. CharlesArize表示:

    Exponent Finance is redefining DeFi lending by providing secure, transparent, and high-yield investment solutions. Through smart contract-powered lending pools, Exponent Finance DeFi platform allows users to borrow and lend crypto assets with optimal efficiency and minimal risk. Whether you’re looking to earn passive income through staking or access instant liquidity, Exponent Finance offers a decentralized, non-custodial, and user-friendly solution to meet all your financial goals in the crypto ecosystem. https://exponent.ink

  7. Franklor表示:

    Cytonic is revolutionizing blockchain security with advanced cybersecurity solutions tailored for Web3 applications. By integrating decentralized encryption, AI-powered threat detection, and smart contract auditing, Cytonic ensures maximum protection against cyber threats. Whether you’re securing DeFi protocols, NFTs, or enterprise blockchain systems, Cytonic’s cutting-edge security technology provides the highest level of data integrity and protection. https://cytonic.cc

  8. EdwardKergy表示:

    продажа аккаунтов https://birzha-akkauntov.ru

  9. DannyTwisp表示:

    Flaunch is the leading blockchain gaming launchpad, designed to help game developers and investors thrive in the Web3 gaming ecosystem. By offering secure token launches, NFT integrations, and decentralized crowdfunding, Flaunch enables game creators to fund, develop, and scale their projects with full transparency and community-driven support. Whether you’re a developer or an investor, Flaunch provides the tools to connect and grow in the blockchain gaming space. https://flaunch.tech

  10. MatthewTut表示:

    купить аккаунт на бирже магазин аккаунтов

  11. Williszew表示:

    http://indiamedfast.com/# cheapest online pharmacy india

  12. Randallvot表示:

    DEQ Finance is revolutionizing decentralized trading by offering a seamless, secure, and efficient crypto exchange experience. Built with cutting-edge blockchain technology, DEQ Finance provides traders with fast transaction speeds, deep liquidity, and a transparent trading environment. Whether you’re a beginner or a professional trader, DEQ Finance delivers high-performance DeFi solutions tailored to modern trading needs. https://deq.li

  13. Arthurhow表示:

    http://mexicanpharminter.com/# reliable mexican pharmacies
    canadian pharmacy com

  14. Georgewhend表示:

    cheapest online pharmacy india: online medicine shopping in india – online medicine shopping in india

  15. JamesGag表示:

    cheapest online pharmacy india: online medicine shopping in india – online medicine shopping in india

  16. Arthurhow表示:

    https://indiamedfast.com/# buying prescription drugs from india
    canada online pharmacy

  17. Montebeera表示:

    canadian medications most trusted canadian pharmacies online buy prescription drugs from canada cheap

  18. I do enjoy the way you have presented this specific problem and it really does give me personally some fodder for thought. Nonetheless, because of what precisely I have seen, I simply trust when the actual feed-back pack on that people continue to be on point and don’t get started upon a soap box of the news du jour. Yet, thank you for this exceptional piece and whilst I do not necessarily go along with this in totality, I respect the point of view.

  19. Wow, this article is mind-blowing! The author has done a tremendous job of conveying the information in an compelling and informative manner. I can’t thank him enough for offering such priceless insights that have definitely enlightened my knowledge in this subject area. Bravo to him for producing such a masterpiece!

  20. Williszew表示:

    https://mexicanpharminter.shop/# reliable mexican pharmacies

  21. A love triangle soon develops among Miles, his pc (who later identifies himself as Edgar), and Miles’s neighbor, a pretty cellist named Madeline Robistat.

  22. Georgewhend表示:

    India Med Fast: india pharmacy without prescription – cheapest online pharmacy india

  23. Arthurhow表示:

    https://mexicanpharminter.com/# Mexican Pharm International
    pharmacy com canada

  24. Montebeera表示:

    canadian pharmacy no scripts Inter Pharm Online canadian mail order pharmacy

  25. Williszew表示:

    http://indiamedfast.com/# india online pharmacy store

  26. Arthurhow表示:

    http://mexicanpharminter.com/# Mexican Pharm Inter
    cross border pharmacy canada

發佈留言

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