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

  1. AndreFuh表示:

    Welcome to Stargate Finance
    Stargate Finance is revolutionizing the way you engage with decentralized financial services. Our platform is designed to offer a secure, efficient, and user-friendly experience for all your financial needs in the world of decentralized finance.
    Stargate Finance
    Why Choose Stargate Finance?
    In the rapidly evolving world of decentralized finance (DeFi), Stargate Finance stands out as a trusted platform due to its innovative solutions and user-centric approach. Here are some reasons to choose us:

    Seamless integration with major blockchain ecosystems
    Advanced security protocols to protect your assets
    User-friendly interface for beginners and experts alike
    Core Features of Stargate Finance
    Stargate Finance provides a variety of features to enhance your DeFi experience, including:

    Cross-Chain Transactions: Safely send and receive assets across different blockchain networks.
    Liquidity Provision: Earn rewards by providing liquidity to various liquidity pools.
    Yield Farming: Maximize your returns through strategic yield farming opportunities.
    How to Get Started
    Getting started with Stargate Finance is simple:

    Visit our official website and create an account.
    Connect your crypto wallet and fund your account with preferred assets.
    Explore our platform’s features and start managing your investment portfolio.

  2. These religions embrace Judaism, Christianity, and Islam, in addition to Zoroastrianism, a faith based by the historic Persian prophet Zoroaster.

  3. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You definitely know what youre talking about, why throw away your intelligence on just posting videos to your blog when you could be giving us something enlightening to read?

  4. Bradleygoath表示:

    cheap priligy dapoxetine price priligy maxpharm

  5. Firoza stone is known for its healing powers and mesmerizing blue-inexperienced shade that makes it distinctive.

  6. 渋い 診断表示:

    Zoroastrianism enters recorded historical past within the mid-5th century BCE.

  7. StevenNub表示:

    priligy max pharm: priligy – dapoxetine price

  8. Malcolm Ramsay Campbell, Commander, Metropolitan Police.

  9. Danieljek表示:

    order amoxicillin 500mg https://amoxilcompharm.com/# amoxicillin tablet 500mg

  10. Intelligence and Strength come second, and they’re going to depend upon each stat necessities (although intelligence shouldn’t be an issue for a minion construct), as well as whether or not you’re going to be crafting a Life or Vitality Shield ring (since the 2 stats present either flat life or a rise to your complete power shield, every little bit goes a long way in the long run).

  11. On December 6, 2018, the primary trial of the case was held.

  12. This web page was last edited on 11 January 2024, at 03:Fifty five (UTC).

  13. 気色顔表示:

    Jane McGranaghan, Valuation Technician, Board of Inland Income.

  14. O’Kelly, Emma (15 March 2021).

  15. This set of 12 dual-coloured towels will solely set you again $17 (that comes out to lower than $2 a towel), but they’re made of excessive-quality ring spun cotton.

  16. Maybe you would like to look utterly different?

  17. xxx_klma表示:

    . [url=https://www.writeablog.net/ofcuw8pyqh]https://www.writeablog.net/ofcuw8pyqh[/url] .

  18. Lieutenant-General Gerald William Lathbury, CB, DSO, MBE (34834), late Infantry.

  19. September 9, 1927. p.

  20. I recommend investing in nice curl products like L’Oréal’s Curl Expression line.

  21. Captain (performing) Percival Douglas Read, 14th Hampshire Battalion, Dwelling Guard.

  22. Young youngsters have small stomachs and are learning what foods they like and dislike.

  23. There are not any exhausting fast deer and rabbit resistant bulbs, but these varieties appear to draw them the least: daffodils, crown imperial, siberian squill, allium, fritillaria, grape hyacinth, bluebells, canine-tooth violet, checkered lily, glory-of-the-snow, winter aconite, and snowdrop.

  24. FreddieDIG表示:

    How to Securely Log Into Debank: A Step-by-Step Guide
    Logging into your Debank account is the first step towards managing your DeFi portfolio. Ensuring that your login credentials remain secure is crucial for protecting your investments. In this guide, we’ll walk you through the process of logging into Debank safely and efficiently.
    Debank airdrop
    Step 1: Visit the Official Debank Website
    Start by navigating to the official Debank website. Avoid using search engine results to prevent phishing attacks. The URL should be .

    Step 2: Click on the Login Button
    On the homepage, locate the Login button usually positioned at the top right corner of the page. Click on it to proceed to the login page.

    Step 3: Enter Your Credentials
    Input your registered email address and password. Ensure your password is strong, combining letters, numbers, and symbols to enhance security.

    Step 4: Two-Factor Authentication
    It’s recommended to enable Two-Factor Authentication (2FA) for an additional security layer. This can be done using an app like Google Authenticator. Enter the code generated by your 2FA app to continue.

    Step 5: Secure Your Account
    Regularly Update Your Password: Change your password every 3-6 months.

    Use a Password Manager: Helps store and recall complex passwords without difficulty.

    Monitor Account Activity: Regularly check for any unauthorized access or activity.

    Additional Tips for Staying Safe Online
    Be vigilant about where you input your credentials. Always ensure that you have a secure and reliable internet connection. Avoid accessing your Debank account on public Wi-Fi networks, which might be unsecured.

    By following these guidelines, you can enhance the security of your Debank login process and safeguard your investments effectively. Stay aware of the latest security practices and updates from Debank to keep your account secure.

  25. Kiema Munyalo, Assistant Inspector, Kenya Police Drive.

  26. Probably the most-prized Turquoise color is a good, intense, medium blue, generally known as robin’s egg blue or sky blue within the trade.

  27. Thomasdag表示:

    Base is for everyone.
    Base Bridge is a cutting-edge solution facilitating smooth transfers between different blockchain networks. By creating a seamless link, it reduces the complexity and cost of blockchain transactions.
    base bridge eth
    What is Base Bridge?
    Base Bridge is a cutting-edge solution facilitating smooth transfers between different blockchain networks. By creating a seamless link, it reduces the complexity and cost of blockchain transactions.

    Key Features of Base Bridge
    Interoperability: Connects multiple blockchain networks, allowing for smooth asset exchange.

    Cost Efficiency: Reduces transaction fees significantly.

    Security: Leverages advanced encryption to protect transactions.

    Scalability: Easily adapts to increasing volumes of transactions without compromising speed.

    Benefits of Using Base Bridge
    Incorporating Base Bridge into your blockchain strategy offers numerous benefits:

    Simplified Transactions: Eliminates the need for complicated cross-chain processes.

    Faster Settlements: Enjoy quicker transaction confirmations.

    Cost-Effective Operations: Lower fees mean more sustainable transactions.

    Improved Security: Benefit from enhanced protection against fraud and hacking.

  28. Thus this a part of the home is typically known as the Henry VIII wing, though the King by no means visited.

發佈留言

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