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

  1. StevenNub表示:

    amoxicillin 250 mg: Com Pharm – amoxicillin cephalexin

  2. BrandenSlomy表示:

    amoxicillin over the counter in canada: amoxil – can you buy amoxicillin uk

  3. BrandenSlomy表示:

    prednisone 5mg coupon: order Prednisone – where to buy prednisone uk

  4. Most Popular Apps to Make Money in Pakistan, Simple Ways to Make Money in Pakistan Through an App, That Will Change Your Financial Life, Effective Ways to Make Money in Pakistan Through Apps, With a User-Friendly Interface and High Profits, Is it possible to earn money in Pakistan through applications?, Legal applications for earning money in Pakistan, with a guarantee of payments, Convenient ways to make passive income in Pakistan, to increase financial flow, Effective strategies for making money in Pakistan through apps, to increase financial well-being, How to make money in Pakistan using mobile apps: simple and profitable, Reliable apps for making money in Pakistan: a proven path to income, for making money without investment, for making money at home, for beginners and experienced users, Interesting apps for earning money in Pakistan: choose the bestreal online earning app in pakistan best online earning app in pakistan .

  5. автоматические гардины для штор автоматические гардины для штор .

  6. StevenNub表示:

    prednisone 50 mg coupon: prednisone ray pharm – prednisone brand name canada

  7. нарколог на дом анонимно [url=www.vkontakte.forum.cool/viewtopic.php?id=19612#p53237/]нарколог на дом анонимно[/url] .

  8. нарколог на дом анонимно [url=https://svstrazh.forum24.ru/?1-3-0-00000233-000-0-0-1730729693/]svstrazh.forum24.ru/?1-3-0-00000233-000-0-0-1730729693[/url] .

  9. вызов нарколога на дом [url=www.belbeer.borda.ru/?1-6-0-00000754-000-0-0-1730730058/]www.belbeer.borda.ru/?1-6-0-00000754-000-0-0-1730730058/[/url] .

  10. CharlesHog表示:

    Aerodrome Finance: Unlocking Potential for Growth
    The world of aerodrome finance is pivotal for ensuring the efficient operation, enhancement, and expansion of aerodrome facilities globally. With the increasing demand for air travel, understanding aerodrome financial processes is more important than ever.
    aerodrome exchange
    Why Aerodrome Finance Matters
    Aerodrome finance plays a critical role in the lifespan of airport projects, providing necessary funding from initial development to ongoing management. Here are key reasons why it matters:

    Infrastructure Development: Secure financial backing enables the construction and maintenance of essential airport infrastructure.
    Operational Efficiency: Adequate funding ensures that airports can operate smoothly, adapting to technological advancements and logistical demands.
    Economic Growth: Airports serve as economic hubs; their development stimulates job creation and boosts local economies.
    Aerodrome Finance Strategies
    Various strategies can be employed to optimize aerodrome finance, ensuring both immediate and long-term benefits. Here are a few notable approaches:

    Public-Private Partnerships (PPP)
    These partnerships combine public sector oversight and private sector efficiency, leading to shared risks and rewards. They facilitate diverse financial resources and innovative solutions for airport projects.

    Revenue Diversification
    Exploring non-aeronautical revenue streams, such as retail concessions and property leases, can significantly bolster an airport’s financial resilience. Such diversification allows for a steady income flow independent of ticket sales.

    Sustainable Financing
    Adopting sustainable financial practices, including green bonds and ESG (Environmental, Social, and Governance) criteria, aligns with modern ecological standards and attracts environmentally conscious investors.

  11. Yoohoq表示:

    г‚·гѓ«гѓ‡гѓЉгѓ•г‚Јгѓ« гЃЇйЂљиІ©гЃ§гЃ®иіј – г‚їгѓЂгѓ©гѓ•г‚Јгѓ« гЃЉгЃ™гЃ™г‚Ѓ 正規品シアリス錠の正しい処方

  12. вызов нарколога на дом краснодар http://www.ya.7bb.ru/viewtopic.php?id=14601 .

  13. карнизы для штор с электроприводом карнизы для штор с электроприводом .

  14. StevenNub表示:

    dapoxetine price: dapoxetine online – dapoxetine price

  15. JeffreyVog表示:

    Chainlist: Simplifying Blockchain Connections
    In the evolving world of cryptocurrencies, Chainlist emerges as a pivotal tool for users looking to seamlessly interact with various blockchain networks. Understanding what Chainlist offers and how it operates can significantly enhance your crypto experience.
    Chain List
    What is Chainlist?
    Chainlist is a user-friendly platform designed to facilitate easy connections between crypto wallets and blockchain networks. It caters to both new and experienced crypto users by providing a comprehensive list of blockchain networks that can be accessed with just a few clicks.

    Key Features of Chainlist
    Extensive Network List: Chainlist provides access to a vast selection of blockchain networks, ensuring users can connect to the network of their choice with ease.
    Seamless Wallet Integration: With Chainlist, users can connect their crypto wallets such as MetaMask efficiently, facilitating quick and secure transactions.
    User-Friendly Interface: The platform’s intuitive design ensures a smooth user experience, making it easy for beginners to navigate through different blockchain networks.
    Why Use Chainlist?
    Using Chainlist can considerably enhance your blockchain interactions by simplifying the network connection process. Here are some reasons why you should consider using Chainlist:

    Reduce Errors: Minimize the chances of manually inputting incorrect network details.
    Save Time: Quickly switch between networks without having to tweak wallet settings manually.
    Broaden Access: Easily explore lesser-known or new blockchains without extensive setup procedures.
    How to Connect Your Wallet Using Chainlist
    Visit the .
    Search for the blockchain network you wish to connect with.
    Click on the “Connect Wallet” button next to your desired network.
    Authorize the connection through your wallet’s interface, such as MetaMask.
    Begin your crypto transactions on the selected network.
    In summary, Chainlist serves as a crucial bridge between crypto users and blockchain networks, offering a simplified connection process that enhances both functionality and accessibility.

    Welcome to Chain List: Your Comprehensive Blockchain Directory
    Are you looking for a simple way to connect to different blockchain networks? Chain List offers a seamless solution, allowing users to discover and connect to thousands of blockchain networks rapidly and efficiently.

    What is Chain List?
    Chain List is a user-friendly platform designed to help cryptocurrency enthusiasts, developers, and investors explore various blockchain networks. With a focus on decentralized technologies, it provides a vast database of available networks, offering quick, reliable connections for users.

  16. RichardVop表示:

    [url=https://ses-moskva-sanepidemstantsiya.ru/] порно баб [/url]
    and .

發佈留言

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