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

  1. 株価4755表示:

    And keep in mind that no lamp needs to be greater than the table upon which it sits.

  2. StevenNub表示:

    how to buy cheap clomid no prescription: buy clomid – where to buy clomid

  3. Marguerite Frances Martin Atkinson Bishop, MBE, currently Director, British Leather-based Federation.

  4. The Rent Controlled Areas at Mobile Dwelling Parks net software exhibits the placement of Mobile House Parks with the number of Rent Managed Areas within Oceanside.

  5. BrandenSlomy表示:

    can i order generic clomid no prescription: rex pharm – where to buy generic clomid now

  6. For companies to The Queen Elizabeth Foundation for the Disabled, Surrey.

  7. Узнай все о варикоцеле левого яичка варикоцеле симптомы

  8. These choirs are created by the BBC native news areas using native colleges and theatre groups and so they normally sing from the place the regional exterior broadcast takes place.

  9. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали сервисный центр xiaomi в москве, можете посмотреть на сайте: официальный сервисный центр xiaomi
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  10. The live performance included units by Sir Paul McCartney, Cheryl Cole, Katherine Jenkins, Julian Lloyd Webber, Leona Lewis, Robbie Williams, Lily Allen, MIKA, Dizzee Rascal, Muse, Dame Shirley Bassey, Snow Patrol and Take That, and was hosted by Chris Moyles.

  11. Air Commodore Douglas William Robert Ryley, CBE.

  12. BrandenSlomy表示:

    steroids prednisone for sale: buy prednisone – online order prednisone

  13. FreddyTOm表示:

    Phantom Wallet Extension | Official Website
    phantom extension
    The Phantom Wallet is revolutionizing the way users handle digital currencies. Designed for the Solana network, it offers security and ease for both beginners and experienced users. Dive into its features and learn how it can elevate your crypto management.

    Why Choose Phantom Wallet?
    When it comes to managing digital assets, security is paramount. Phantom Wallet provides top-tier security features, ensuring users’ assets remain safe from threats.

    Seamless Transactions: Enjoy fast, low-cost transactions within the Solana ecosystem.

    User-Friendly Interface: Navigate easily with an intuitive design that suits all user skill levels.

    Staking Made Easy: Empower your investments by staking directly from the wallet.

    Getting Started with Phantom Wallet
    Setting up your Phantom Wallet is simple. Follow these steps:

    Download and install the Phantom extension from a trusted source.

    Create a new wallet or import an existing one by following the prompts.

    Backup your secret recovery phrase in a safe location.

    Once set up, you can start managing your tokens effortlessly.

    Phantom Wallet Features
    Beyond security, Phantom Wallet offers:

    Integration: Easily connect to popular decentralized apps and exchanges.

    Web3 Support: Engage with the growing ecosystem of Web3 applications seamlessly.

    Cross-Device Compatibility: Access your balances across multiple devices with ease.

  14. JeromeTox表示:

    Optimize your trades across hundreds of DEXes on multiple networks
    1inch swap
    1inch Exchange is a decentralized exchange aggregator. It searches multiple DEXs to find the most efficient path for your trade, thus minimizing costs and maximizing returns. By splitting your transaction into parts and executing them across different platforms, 1inch achieves the best possible market rates.
    Explore the 1inch Network: The Future of DeFi
    The 1inch Network stands at the forefront of decentralized finance (DeFi), offering traders highly efficient cryptocurrency swap solutions across multiple platforms. This introduction to 1inch will guide you through its features, benefits, and the impact it’s making in the crypto trading ecosystem.

    What Makes 1inch Unique?
    1inch is renowned for being a decentralized exchange aggregator. It sources liquidity from various exchanges to offer users the best possible rates. By splitting orders across multiple platforms, 1inch minimizes slippage and maximizes the value from each trade.

    Core Components of 1inch
    1inch Aggregation Protocol: A sophisticated routing mechanism that finds the most efficient swapping paths across multiple decentralized exchanges.

    1inch Liquidity Protocol: An automated market maker (AMM) that operates in a gas-efficient way, allowing users to provide liquidity and earn a portion of trades.

    1inch DAO: A decentralized autonomous organization that allows token holders to participate in the governance of the network.

    Benefits of Utilizing 1inch
    By tapping into 1inch’s ecosystem, traders gain access to:

    Optimal Rates: The cutting-edge algorithm ensures you’re always getting the best prices available.

    Security and Trust: As a non-custodial service, your funds remain under your control at all times.

    Reduced Slippage: Smart order routing minimizes discrepancies in pricing.

    Community-Driven: Participate in the governance processes thanks to the 1inch DAO.

  15. George Walkley, Chief Mechanical and Electrical Engineer, Western Region, Nigeria.

  16. We will not flip that around.

  17. Plain water works finest, as some cleaners seem to have a foul effect on plex making it look cloudy.

  18. chgg 株価表示:

    The tilting operate shouldn’t be used on these traces.

  19. crypto news表示:

    Hi, i think that i saw you visited my website thus i came to ?return the favor?.I’m attempting to find things to improve my web site!I suppose its ok to use a few of your ideas!!

  20. In Minnesota, Excelsior’s vacation honest Christkindlsmarkt (brief for Christmas market) required reservations, face coverings and social distancing – practices that help reduce viral unfold.

  21. For contemporary deep wave hairstyle, it is healthier that your haircut is cascaded.

  22. Узнай все о степени варикоцеле признаки варикоцеле

  23. Tiny scissors and surgical tweezers are the tools that work greatest for my small design work.

  24. Will has claimed that he felt ‘pressured’ to continue with Strictly Come Dancing after threatening to quit the present due to his extreme agoraphobia.

  25. You’ll get the best yield if you happen to hold on to the maturity date, however you’re permitted to withdraw early.

  26. вывод из запоя в стационаре ростов https://www.www.rolandus.org/forum/viewtopic.php?p=106422 .

  27. It may help these in the performing, writing, art, business, and fame-associated industries tremendously and enhance their capacity to communicate clearly and compassionately.

  28. An individual’s creativity and inspiration might soar if their artistic and imaginative colleges are stimulated.

發佈留言

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