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

16,469 Responses

  1. gay sex表示:

    Undeniably consider that that you said. Your favourite justification seemed to be at the net the easiest thing to consider of. I say to you, I certainly get irked even as people think about concerns that they just don’t recognise about. You controlled to hit the nail upon the highest as well as defined out the whole thing with no need side-effects , other people can take a signal. Will probably be back to get more. Thanks

  2. I relish, result in I discovered just what I used to be looking for. You have ended my four day long hunt! God Bless you man. Have a nice day. Bye

  3. online casino表示:

    Wow, fantastic blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is great, as well as the content!

  4. online casino表示:

    I can’t believe how amazing this article is! The author has done a tremendous job of presenting the information in an engaging and educational manner. I can’t thank her enough for sharing such precious insights that have certainly enlightened my awareness in this topic. Hats off to him for creating such a gem!

  5. StevenLoN表示:

    Unlock the Power of Eigenlayer
    As the blockchain landscape evolves, Eigenlayer emerges as a beacon of innovation, offering robust solutions to enhance blockchain security and customization. But what exactly does Eigenlayer bring to the table?
    eigenlayer claim
    Revolutionizing Blockchain Security
    Security is paramount in the blockchain world, and Eigenlayer takes this seriously. By leveraging state-of-the-art technology, Eigenlayer provides an unparalleled layer of protection for blockchain protocols. This ensures that transactions are not only secure but also reliable.

    Advanced Encryption: Protects data integrity and confidentiality.
    Scalable Solutions: Ensures that security measures grow with your network’s demand.
    Customization like Never Before
    One of the most compelling features of Eigenlayer is its customization capabilities. Understanding that each blockchain project has unique needs, Eigenlayer offers a flexible architecture allowing projects to tailor solutions to their specific requirements.

    Modular Design: Adapts to various use cases without sacrificing performance.
    Interoperability: Seamlessly integrates with existing blockchain systems.
    Empowering Blockchain Ecosystems
    By providing these advanced features, Eigenlayer doesn’t just offer protection and customization; it empowers blockchain developers to push the boundaries of what’s possible. With Eigenlayer, the limitations often faced in blockchain scalability and security are becoming a thing of the past.

    Whether you are a developer seeking better security solutions or an entrepreneur aiming to launch your blockchain project with tailor-made features, Eigenlayer provides the tools and the support you need to succeed in the competitive digital landscape.

    Explore the potential of Eigenlayer today, and step into the future of blockchain technology with a partner committed to your success.

  6. The root of your writing whilst sounding reasonable at first, did not sit very well with me personally after some time. Somewhere within the paragraphs you managed to make me a believer unfortunately just for a while. I still have a problem with your leaps in logic and you might do well to fill in those gaps. In the event you actually can accomplish that, I would certainly be impressed.

  7. StevenNub表示:

    priligy: priligy max pharm – Priligy tablets

  8. Dereketerm表示:

    amoxicillin order online no prescription: amoxil – amoxicillin 875 mg tablet

  9. RobertSam表示:

    What is DeBridge Finance?
    DeBridge Finance is an innovative solution designed to facilitate seamless cross-chain blockchain operations. It empowers developers and users by allowing the transfer of data and assets across different blockchain networks efficiently and securely.
    [url=https://dbrlifi.org/]Debridge[/url]
    Key Features of DeBridge Finance
    DeBridge Finance stands out due to its remarkable features which include:

    Interoperability: The platform provides effective interoperability between multiple blockchains, eliminating the boundaries that exist.
    Security: By leveraging advanced security protocols, DeBridge ensures the safe transit of data and assets.
    Scalability: It is designed to handle a growing number of transactions without compromising on performance.
    How Does DeBridge Finance Work?
    DeBridge Finance operates through a combination of smart contracts and decentralized communication protocols. These components work together to authenticate and execute cross-chain data and asset transfers swiftly and securely.

    Smart Contracts
    The platform utilizes smart contracts to automate processes and ensure trustless operations across different chain environments.

    Decentralized Communication
    Communication across blockchains is made possible through a decentralized message protocol, enabling effective data sharing.

    Benefits of Using DeBridge Finance
    Choosing DeBridge Finance for cross-chain operations brings several advantages:

    Cost-Effectiveness: By integrating various blockchains, it reduces the cost and complexity of using multiple networks.
    Developer-Friendly: Offering robust tools and resources, DeBridge makes it easier for developers to build cross-chain applications.
    Enhanced User Experience: Users benefit from smoother transactions without the need to switch between different network interfaces.

  10. It?s laborious to find educated folks on this matter, but you sound like you already know what you?re talking about! Thanks

  11. Dereketerm表示:

    priligy: max pharm – buy dapoxetine online

  12. Ynhwzw表示:

    гѓ—гѓ¬гѓ‰гѓ‹гѓі гЃЇйЂљиІ©гЃ§гЃ®иіј – アジスロマイシン йЈІгЃїж–№ г‚ёг‚№гѓ­гѓћгѓѓг‚Ї и–¬е±ЂгЃ§иІ·гЃ€г‚‹

  13. BrandenSlomy表示:

    max pharm: buy dapoxetine online – priligy maxpharm

  14. Dereketerm表示:

    how to get cheap clomid pills: can i order cheap clomid without a prescription – can you get clomid without dr prescription

  15. I discovered your weblog website on google and check a couple of of your early posts. Continue to keep up the very good operate. I simply further up your RSS feed to my MSN News Reader. Seeking ahead to studying more from you later on!?

  16. Excellent read, I just passed this onto a friend who was doing a little research on that. And he actually bought me lunch because I found it for him smile Thus let me rephrase that: Thanks for lunch!

  17. BrandenSlomy表示:

    buy priligy max pharm: max pharm – priligy

  18. Lazrkio表示:

    Официальная покупка школьного аттестата с упрощенным обучением в Москве
    yaoisennari.ekafe.ru/posting.php?mode=post&f=169&sid=7d66876e70c208364c4a3105c8a848a0

  19. online casino表示:

    Heya i am for the first time here. I found this board and I in finding It really useful & it helped me out much. I am hoping to provide something again and help others like you aided me.

  20. bpdb.gov.bd表示:

    This article is a breath of fresh air! The author’s distinctive perspective and perceptive analysis have made this a truly engrossing read. I’m grateful for the effort he has put into crafting such an educational and thought-provoking piece. Thank you, author, for sharing your knowledge and stimulating meaningful discussions through your brilliant writing!

  21. StevenNub表示:

    buy dapoxetine online: buy priligy max pharm – max pharm

  22. gay sex表示:

    Spot on with this write-up, I truly suppose this website wants rather more consideration. I?ll probably be once more to read far more, thanks for that info.

發佈留言

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