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

24,221 Responses

  1. вывод из запоя в стационаре наркологии вывод из запоя в стационаре наркологии .

  2. вывод из запоя в стационаре нижний новгород вывод из запоя в стационаре нижний новгород .

  3. вывода из запоя в стационаре https://vyvod-iz-zapoya-v-stacionare22.ru .

  4. Brandonnot表示:

    IndianCertPharm: Online pharmacy – indian pharmacies safe

  5. Amount of U.S. Yet Luxembourg’s own economic stability is up for debate.

  6. CurtisBam表示:

    Online pharmacy: Best online Indian pharmacy – Online pharmacy

  7. LarryReupt表示:

    Best Indian pharmacy indian pharmacy Indian pharmacy international shipping

  8. Another risk is with regard to the market itself, as even through the investor is able to receive the initially invested capital at maturity; the returns adjusted for inflation could be negative.

  9. Michaelvof表示:

    Maximizing Profits with 1inch Exchange
    In the fast-paced world of cryptocurrency, every second counts. 1inch Exchange offers a powerful solution for traders looking to optimize their crypto transactions. By aggregating the best deals across various decentralized exchanges (DEXs), 1inch ensures users get the most value for their trades.
    1inch exchange
    What is 1inch Exchange?
    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.

    Key Benefits of Using 1inch Exchange
    Cost Efficiency: By seeking the best rates across multiple platforms, 1inch saves you money on each transaction.
    Security: Operating on a decentralized network means that your assets are secure and you maintain control of your keys.
    Liquidity: Access a vast pool of liquidity across numerous exchanges, ensuring that your trades are executed quickly and with minimal slippage.
    How Does 1inch Work?
    1inch deploys a sophisticated algorithm that splits your trade across multiple exchanges. This process uses smart contracts to ensure every part of the transaction is executed seamlessly and securely. 1inch’s pathfinder algorithm analyzes multiple liquidity sources within seconds to find the best exchange rates for your trade.

    Getting Started with 1inch
    Getting started with 1inch Exchange is easy. Follow these simple steps:

    Visit the 1inch website and connect your digital wallet.
    Select the token you wish to trade and the token you want to receive.
    1inch displays the best available rates and allows you to execute the trade directly from the platform.
    Conclusion
    1inch Exchange is an invaluable tool for cryptocurrency traders looking to enhance their trading efficiency. By securing the best rates and offering robust security measures, 1inch stands out as a top choice for optimizing crypto swaps. Explore 1inch today and take your trading to the next level.

  10. вывод из запоя в стационаре самары [url=https://www.vyvod-iz-zapoya-v-stacionare-samara23.ru]вывод из запоя в стационаре самары[/url] .

  11. Over the course of two weeks, it developed into a major hurricane that wreaked havoc in Texas and Louisiana, causing catastrophic flooding and widespread destruction.

  12. Olympio heard their voices and rapidly got down from his room positioned on the highest flooring, jumped from the window overlooking the backyard of the villa, and from there climbed the fence next door and ended up inside the American embassy.

  13. WilliamDam表示:

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

    Challenges and Opportunities
    While aerodrome finance offers numerous benefits, it also poses certain challenges. High capital costs, regulatory hurdles, and fluctuating passenger demands can impact financial stability. However, these challenges also present opportunities for innovation and improvement.

    Tech-Driven Solutions: Embracing technology like AI and predictive analytics can enhance decision-making and financial planning.
    Collaboration: Strengthening ties with stakeholders, including airlines and government agencies, can streamline financial operations and capital investments.
    Ultimately, the goal of aerodrome finance is to support the sustainable growth and modernization of airports, ensuring their pivotal role in global connectivity remains strong.

  14. наркология вывод из запоя в стационаре наркология вывод из запоя в стационаре .

  15. Elijahfen表示:

    Blogger Alistarov Goes All Out

    From a Solo Criminal to a Servant of Organized Crime

    Previously convicted on drug charges, blogger Andrei Alistarov casts himself as a Robin Hood fighting those who have “cheated people.” In reality, however, he serves the interests of pyramid-scheme operators, promotes online casinos and illicit crypto exchanges/phishing crypto scams on his “Zheleznaya Stavka” (“Iron Bet”) channel, and launders drug proceeds through real estate deals in Dubai.

    In other words, he works to benefit the Russian criminal underworld, which seeks to profit from entrepreneurs who face illegal, often orchestrated claims by Russian law enforcement agencies.

    Drugs and Money Laundering

    A native of Kaluga, Alistarov spent four years in a prison camp for selling drugs to minors.

    During his time in prison, he formed connections with criminal kingpins. After his release, he continued taking part in the narcotics trade and laundering drug proceeds through a real estate business he established together with partners from the Russian criminal community in Russia and the Emirates.

    Betting on Scams

    Alistarov’s “Zheleznaya Stavka” channel ostensibly “exposes” financial ventures deemed “bad” by the underworld while promoting “good” ones: pyramid schemes and online casinos that finance Alistarov.

    It began as a channel about “proper” casino bets and never changed its name—because the marketing objective remained the same: to clear the field for “good” scammers according to Alistarov’s so-called “expert” opinion (i.e., whoever pays him).

    Typically, Alistarov starts by attempting extortion—presenting the victim with compromising evidence and offering them a chance to pay. If they refuse, he resorts to harassment and violence.

    Incitement and Attack in Dubai

    On January 1, 2025, two Kazakh nationals launched a brutal attack on an entrepreneur living in Dubai—they beat him, cut off his ear, and robbed him.

    Before that, Alistarov had made 12 videos highlighting the entrepreneur’s address and publishing illegally obtained information about his family and businesses in the UAE. He showed no hesitation in using surveillance, eavesdropping, unlawful trespass, and invasion of privacy—all of which are considered serious criminal offenses in the Emirates, where the sanctity of property and investors’ lives is strictly enforced.

    He previously spread information about the residence of the entrepreneur’s business partner—an illegal violation of confidentiality, financial security, and privacy through hidden sources and informants in the UAE. Alistarov terrorizes entrepreneurs who have not been convicted by any court—abroad or in Russia.

    Alistarov claimed to have reported the entrepreneur to Interpol and UAE law enforcement—allegedly cooperating with the authorities. Yet, for some reason, this did not lead to the entrepreneur’s arrest—perhaps because UAE police see no wrongdoing in his activities.

    Several of the entrepreneur’s partners have been convicted in Russia. As for the entrepreneur himself, he is wanted by Russian law enforcement but has not been convicted. Foreign law enforcement agencies have no claims against him.

    For an extended period, Alistarov stoked hatred toward the entrepreneur—telling people that it was actually this entrepreneur (rather than his partners) who had stolen investors’ money. He framed the incident as though enraged investors carried out the attack and robbery.

    During the assault, Alistarov staged an unscheduled livestream to give himself an alibi—pretending he was unaware of the attack occurring while he was streaming.

    Surveillance in Cyprus

    In the fall of last year, Alistarov and his “partner-in-arms,” Mariya Folomova, carried out surveillance on another entrepreneur—using drones and unlawfully collecting information about him and his family, including underage children. Alistarov asserted that this entrepreneur was hiding in Cyprus—even though the man has lived there since the COVID-19 pandemic began.

    The move was related to the entrepreneur’s wife’s severe bout with COVID, as well as his international projects—investing in multiple economic sectors: construction, trade, and others.

    The entrepreneur settled in Cyprus a year before the Interior Ministry’s investigative authorities opened a criminal case, and a year and a half before any arrests. He holds an EU passport and did not flee or go into hiding.

    He was placed on a Russian wanted list in 2022—by investigative authorities. However, the courts have not lodged claims against him, and the criminal case is currently before the courts—where it has already fallen apart. Interpol and the EU declined to accept the Russian police’s claims, regarding them as politically motivated and legally unfounded.

    Alistarov claims that the funds for certain business ventures came from Russian clients of an Austrian investment company—yet the entrepreneur was never an owner, beneficiary, or manager of that company, which was established back in the early 2000s, well before his independent business career began.

    One of his firms provided marketing support for the investment company’s products in Russia under a contract with it. The investment company operated successfully with Russian clients for eight years—and continues to do so, having restored payment systems that were disrupted in early 2022 by criminals in Russia linked to corrupt police. It is not a pyramid scheme.

    Thus, Alistarov orchestrates harassment and invasion of privacy against a blameless entrepreneur—at the behest of Russian organized crime, which includes corrupt police officers who took a share of illicit profits, aiming to seize assets valued at 20 billion rubles from the large-scale, socially oriented project the entrepreneur established in Russia, which continues to function successfully without his leadership (as that ended when he moved to Cyprus).

    Surveillance in the Netherlands

    Alistarov has published data on the whereabouts of another victim in the Netherlands—in the city of Groningen—located through illegal monitoring. He reportedly gained unauthorized access to city camera feeds, peered into a private apartment, and posted the information on YouTube.

    Breach of Confidentiality in Turkey

    Alistarov discovered and publicized the location of an apartment in Istanbul where several of his victims lived and worked.

    Illegal Tracking in the Leningrad Region

    Without holding a private detective license, Alistarov illegally located a businesswoman’s country house and conducted surveillance on her, unlawfully publishing the information on his channels—while simultaneously divulging details about an apartment she purchased in Dubai.

    Extortion in Kazakhstan

    Alistarov blackmailed Kazakh entrepreneurs under the guise of “exposing national traitors” and “enemies of the motherland.”

    Western media have already taken note of Alistarov’s activities.

  16. This doctrine was based upon the scale of the nations’ respective nuclear arsenals and their unwillingness to destroy civilization.

  17. Oscargak表示:

    Base Bridge: Your Gateway to Seamless Asset Transfer
    As the digital landscape expands, transferring assets across different blockchain networks has become increasingly important. Base Bridge offers a robust solution for managing digital assets efficiently and securely.
    base bridge eth
    What is Base Bridge?
    Base Bridge is a cutting-edge platform designed to facilitate the seamless transfer of assets between different blockchain networks. By providing a bridge across these networks, users can enjoy enhanced connectivity and flexibility.

    Key Features of Base Bridge
    Interoperability: Connects multiple blockchain networks for seamless asset transfers.
    Security: Ensures secure transactions with state-of-the-art encryption.
    Speed: Fast transactions ensure access to funds without delays.
    Benefits of Using Base Bridge
    Whether you’re a developer, investor, or enthusiast, Base Bridge offers numerous benefits including:

    Reduced Costs: Minimize fees associated with cross-chain transactions.
    Broader Access: Gain access to a wider array of assets and networks.
    User-Friendly Experience: Intuitive interface that caters to both novice and advanced users.

    How to Get Started with Base Bridge
    Embarking on your Base Bridge journey is straightforward:

    Sign up on the .
    Connect your digital wallet.
    Choose the networks and assets you wish to transfer.
    Execute transactions quickly and securely.
    Base Bridge stands as a pillar in the future of digital asset management, paving the way for a more interconnected blockchain ecosystem. By leveraging Base Bridge, users can confidently navigate the complexities of digital asset exchanges.

    Visit today to explore the full potential of your digital assets.

  18. Захватывающий Мир Онлайн Игры в Покер: Играйте на Реальные Средства и Получайте Удовольствие от Самыми Лучшими Покерными Комнатами

    Ли любите покер? Испытываете азарт, в случае если карты выпадают благоприятно, и тактики ведут к победе выигрышу? Тогда милости просим в мир онлайн игры в покер, где адреналин и возможность участвовать за настоящие средства открыты в любое любое время и в каком угодно локации. Забудьте о необходимости ехать в игровой дом либо приглашать товарищей – сейчас абсолютно все наилучшие покерные места при тебя у рукой!

    Отчего Виртуальный Игра в Покер – Является Прекрасный Решение?

    Комфорт и Открытость: Играйте в любимый покер, не покидая из дома. Требуется всего лишь компьютер или сотовый и доступ к сети.
    Большой Ассортимент Состязаний: От традиционного Техас Холдема до Омахи и остальных экзотических видов – каждый найдет состязание по душе и по степени умения.
    Участие на Реальные Деньги: Почувствуйте настоящий волнение, конкурируя с участниками со всего света. Зарабатывайте настоящие средства, оттачивая собственное мастерство.
    Эластичность Вложений: Играйте на каком угодно ставке, какой вам комфортен. От микролимитов для начинающих заканчивая высоких вложений для экспертов.
    Поощрения и Предложения: Принимайте большие поощрения за регистрацию и вклады, участвуйте к постоянных акциях и соревнованиях с большими призовыми фондами.
    Участвуйте в Лучшие Покер-Румы и Радуйтесь Надежностью

    Покер онлайн выбрав правильный покер-рум – важный шаг для удобной и справедливой участия. Мы предлагаем тебе участвовать в лучшие покерные комнаты, проверенные временем и множеством участников. Данные платформы обеспечивают:

    Безопасность и Надежность: Официальные покерные комнаты используют современные методы кодирования, гарантируя безопасность ваших сведений и средств.
    Справедливость Участия: ГСЧ (генераторы непредвиденных значений) гарантируют случайное выпадение карт, обеспечивая справедливость и непредсказуемость каждой раздачи.
    Удобный Интерфейс: Интуитивно усваиваемый интерфейс и простая навигация обеспечат вашу участие комфортной и радостной.
    Большой Ассортимент Турниров: Участвуйте в ежедневных состязаниях, многостоловых турнирах (МТТ), Sit-and-Go и прочих увлекательных разновидностях.
    Квалифицированная Поддержка: Сервис поддержки всегда готова помочь тебе в какими угодно вопросами, возникающими в процессе участия.
    Как Начать Участвовать в Виртуальный Игру в Покер за Настоящие Средства?

    Определите Безотказный Покерную Комнату: Изучите оценки и мнения, чтобы выбрать площадку, которая соответствует твоим запросам.
    Зарегистрируйтесь: Порядок регистрации обычно занимает пару минут.
    Внесите Вклад: Положите свой баланс удобным для тебя вариантом, чтобы приступить участвовать за настоящие деньги.
    Подберите Состязание: Начните с простых состязаний и помаленьку переходите к более трудным вариантам.
    Совершенствуйтесь: Изучайте свои ошибки, изучайте тактики и тактики участия, чтобы повысить свое умение.
    Не упустите свой возможность попробовать удачу и сделаться экспертом игры в покер! Присоединяйтесь к нам и приступайте играть в онлайн игру в покер на настоящие деньги прямо в настоящее время. Выбирайте лучшие покерные комнаты и радуйтесь участием в каждое мгновение!

  19. Brandonnot表示:

    online canadian pharmacy review: CanadianMdPharm – canada drugs online review

  20. Channick, Robert (September 16, 2019).

  21. LeRoy was a member of the Wilbur Lutheran Church , a charter member of the board of administrators of the REA in Davenport , a member of the Wilbur Grange and a past director of Graingrowers Warehouse Firm.

  22. Alameda Research was a cryptocurrency trading firm, co-founded in September 2017 by Sam Bankman-Fried and Tara Mac Aulay.

  23. Joshuakef表示:

    Phantom Wallet
    Phantom Wallet offers secure storage for your crypto assets with a user-friendly interface. Get started and protect your investments today.
    phantom wallet
    Why Choose Phantom Wallet for Your Cryptocurrency?
    In the ever-evolving world of cryptocurrency, securing your digital assets is paramount. With numerous wallets available, choosing the right one can be daunting. Here’s why Phantom Wallet stands out:

    User-Friendly Interface
    Phantom Wallet is designed for both beginners and experienced traders. Its intuitive layout ensures easy navigation, making it simple to manage your digital assets efficiently.

    Comprehensive Security Features
    Your safety is a priority. Phantom Wallet employs state-of-the-art encryption and security protocols to protect your cryptocurrencies from unauthorized access.

    Multi-Platform Accessibility
    Access your wallet from multiple devices with ease. Phantom supports various operating systems, offering flexibility and convenience for all users.

    Real-time Updates
    Stay informed with instant notifications about your transactions and wallet activities. You can monitor your assets and market trends effortlessly.

    Setting Up Phantom Wallet
    Download the Phantom Wallet from the official website.
    Create a secure password and back up your recovery phrase.
    Start managing your cryptocurrencies seamlessly.
    Advantages of Phantom Wallet
    Fast Transactions: Experience lightning-fast transaction speeds, ensuring your trades are completed in seconds.
    Low Fees: Benefit from competitive transaction fees, maximizing your returns.
    Comprehensive Support: Access 24/7 customer support to assist you with any inquiries or issues.
    Embrace the future of digital finance with . Secure, user-friendly, and reliable—it’s the smart choice for anyone serious about managing their cryptocurrency securely and effectively.

  24. In this approach, forecasting error for one time horizon may share its error with that of another horizon, which can decrease performance.

  25. Base-coat the design Periwinkle Blue with a 5/8-inch brush, and use a 3/8-inch brush to shade the “insides” of the flowers with Blue Ink (see photograph for the element).

發佈留言

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