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 } }
Welcome to Jumper Exchange
Jumper Exchange is your one-stop destination for seamless cryptocurrency swaps. Dive into an unparalleled trading experience designed for both newcomers and veteran traders.
jumper exchange
Why Choose Jumper Exchange?
Jumper Exchange stands out for several compelling reasons:
User-Friendly Interface: Navigate through our platform with ease, whether you’re trading from a desktop or mobile device.
Fast Transactions: Experience rapid transaction speeds that ensure you never miss out on market opportunities.
Security First: Rest assured that our advanced security protocols protect your assets at all times.
Wide Range of Cryptocurrencies: Access a diverse array of cryptocurrencies to swap and trade effortlessly.
How to Start Trading
Register for an account using a simple signup process.
Verify your identity quickly and securely.
Fund your account and start swapping your preferred cryptocurrencies.
Our educational resources also provide you with insights and strategies to help you make informed trading decisions every step of the way.
Join Our Community
When you sign up with Jumper Exchange, you join a vibrant community of crypto enthusiasts eager to share experiences and insights. Participate in our forums, and stay updated with the latest news and trends.
Support and Resources
Our dedicated support team is available 24/7 to assist you with any questions or concerns. Access our comprehensive resource center for help guides, FAQs, and the latest platform updates.
Make Jumper Exchange your go-to platform for a streamlined, secure, and efficient crypto trading experience.
There’s noticeably a bundle to find out about this. I assume you made certain nice points in options also.
клиника вывод из запоя ростов [url=http://www.vyvod-iz-zapoya-rostov229.ru]клиника вывод из запоя ростов[/url] .
вызвать капельницу от запоя на дому [url=http://vyvod-iz-zapoya-rostov228.ru/]вызвать капельницу от запоя на дому[/url] .
check phantom Download
special info phantom Extension
I believe one of your advertisements triggered my browser to resize, you might want to put that on your blacklist.
In 1961 work unfold to Christians in issue in Asia, and in 1965 to Africa.
Sallehuddin bin Awang Pekan.
What is Curve Finance?
Curve Finance is a decentralized exchange platform designed to facilitate low-cost, low-slippage trades of stablecoins and other assets. Built on the Ethereum network, Curve.fi optimizes trading and liquidity provision, making it a popular choice among decentralized finance (DeFi) users.
curve finance
How Does Curve Finance Work?
Curve Finance employs an automated market maker (AMM) model, which eliminates the need for traditional order books. Instead, it uses liquidity pools to match trades and provide liquidity. This system is particularly effective for stablecoin exchanges, where price fluctuations are minimal.
Key Features of Curve Finance
Low Slippage: By focusing on stablecoins, Curve minimizes price volatility during trades.
Efficient Trading: Curve’s AMM model enables quick and efficient transactions.
Liquidity Incentives: Users providing liquidity earn rewards in the form of trading fees and CRV tokens.
Benefits of Using Curve Finance
Curve Finance offers numerous benefits for users looking to optimize their cryptocurrency trading experience:
Competitive Rates: By reducing slippage and transaction fees, Curve provides a cost-effective solution for stablecoin trades.
Decentralized Control: Users benefit from the security and autonomy of a decentralized network.
Yield Farming Opportunities: Beyond trading, users can engage in yield farming, earning additional income by supplying liquidity.
How to Get Started with Curve Finance
To begin using Curve, you need an Ethereum wallet, such as MetaMask, and some ETH to cover gas fees. Here’s a quick guide to get you started:
Connect your Ethereum wallet to Curve.fi.
Select a trading pair from the available liquidity pools.
Enter the amount you wish to trade or provide as liquidity.
Confirm the transaction and pay the necessary gas fees.
By following these simple steps, you can start taking advantage of the low-cost, low-slippage trades that Curve Finance offers.
Conclusion
Curve Finance is a robust platform for anyone looking to engage in efficient cryptocurrency trading. With its focus on stablecoins and low slippage, Curve.fi provides users with an optimized trading experience backed by the security of decentralized finance. Whether you’re a trader or a liquidity provider, Curve Finance offers tools and incentives to enhance your DeFi journey.
Yim Wing Chun is traditionally stated to be a woman who developed a mode of hand-to-hand combat to get out of an arranged marriage with a merciless man.
Step 5: When the hounds “awaken,” the gamers stare closely at every others’ eyes and recommend one or more individuals they consider to be the fox.
The rupture technique of the earthquake indicate the highly oblique movement between the two tectonic plates.
цены на вывод из запоя на дому цены на вывод из запоя на дому .
Обратите внимание, гейы!
Желаете попасть в пространство виртуальных-игр и выиграть действительные финансы? Тогда вам тут! Топ лучших превосходных казино 2025
Наш telegram-канал — ваш гид в мир лучших виртуальных-игр в России! Мы собрали ТОП-10 надежных игровых площадок, где вы сможете играть на финансы и забрать свои доходы без проблем.
Что вас ждет:
Достоверные рекомендации и ранги Казино с турнирами от действительных игроков. Отличная статус всякого ресурса проверена годами и пользователями. Неоплачиваемая запись и мгновенный доступ на всех ресурсах. Активные дубликаты для посещения к вашему излюбленному игровому сайту в каждый час. Мобильная софт для комфортной проведения времени где угодно.
Почему нас?
Проверенные и проверенные казино с лучшими параметрами для проведения времени. Защита ваших сведений и транзакций обеспечена. Новые новости и обновления пространства виртуальных-казино в Российской Федерации.
Platte in 1944 and had 4 youngsters.
isotretinoin 20mg sale – zyvox 600 mg us buy zyvox 600 mg generic
Although one further novel featuring the Eighth Doctor (Worry Itself by Nick Wallace) was revealed below the Past Doctor Adventures line before BBC Books determined to retire the PDAs as well, that e book takes place prior to Timeless.
Пoker В сети: Твой Руководство в Область Азартных Планов
Хотите незабываемых переживаний и когнитивных задач? Сфера покера в интернете готов принять Вас! Эта игра не только увлекательная развлечение, это целая сфера, в которой действительно переплетаются расчеты, психология и план. Подготовлены погрузиться в это увлекательный пространство?
Какие факторы отличают покер онлайн настолько заманчивым?
Легкость доступа: Поиграть возможно где хотите и в любой момент угодно, необходим лишь соединение в сеть. Многообразие: Множество видов и вариантов игры (Техасский Холдем Холдем poker, Омаха poker и другие). Возможность получить: Poker в сети предоставляет не только веселиться, и и зарабатывать на финансы. Конкуренция: Вы можешь соревноваться с пользователями со всей планеты земли. Развитие: Вы можешь улучшать твои навыки и совершенствовать план.
С какого момента стартовать начинающему?
Выбор достоверного платформы: Найдите проверенный и отличный платформа или игровой зал с отличными рекомендациями и оценкой. Регистрационная процедура: Этап регистрационного процесса обязательно оказаться простым и доступным. Изучение руководств: Стартуйте с базовых инструкций выбранной разновидности Poker. Тренировочный режим: Попробуйте сыграть в тренировочном режиме, чтобы понять механику процесса. Начальный взнос: Стартуйте играть на настоящие финансы с первоначальным вкладом. Контроль финансами: Контролируйте твоими финансами с умом, не играться на крайние финансы.
Каким образом отобрать хороший игровой зал?
Сертификат: Присутствие лицензии говорит о надежности сайта. Темп вывода: Обратите взгляд на темп и методы снятия денег. Техподдержка содействие: Качественная и быстрая помощь посодействует разрешить все проблемы. Мобильный приложение: Комфортное мобильное версия предоставит поиграть в каждый час и в любом уголке. Поощрения и спецпредложения: Начальные подарки и частые акции способны поднять ваш начальный капитал.
Рекомендации для новых игроков:
Не торопитесь: Стартуйте с малых ограничений, чтобы приобрести опыта. Учитесь: Регулярно совершенствуйте твои способности, просматривайте руководства и наблюдайте видео. Изучайте: Изучайте вашу развлечение, ищите недочеты и трудитесь над ними. Контролируйте чувства: Играйте уравновешенно, не поддавайтесь желанию. Играйте ответственно: Не забывайте, что игра – это увлечение, а не путь быстрого обогащения.
Игра в сети Покер онлайн играть 2025 – это захватывающая игра, которая может принести вам не просто развлечение и наслаждение, но также шанс получить реальные деньги. Главное – верно подойти к этому процессам, и победа не заставит себя ждать!
Какой у вас ваш предпочтительный игровой зал? Какой платформа вы считаете отличным для игры на деньги? Делитесь вашим опытом в комментариях!
#покеронлайн #играть в покер #игровой зал #лучшийсайт #регистрационный процесс #выводденег #первоначальный взнос #загрузить #на финансы #мобильная версия #топ #оценка #2025 год
slot siteleri az parayla cok kazandiran slot oyunlar? slot oyunlar?
Scientists have identified an estimated 10% of all species on Earth. Here’s what they found in 2024
[url=https://kra26c.cc]kra28 cc[/url]
A toothy toadstool. A vegetarian piranha with a distinctive mark. And a pygmy pipehorse floating in the Indian Ocean shallows.
These wild wonders were among the hundreds of previously unknown species of animals, plants and fungi that scientists named and described for the first time in 2024, expanding our surprisingly limited knowledge of Earth’s diversity.
“Scientists estimate that we’ve identified only one-tenth of all species on Earth,” said Dr.
Shannon Bennett, chief of science at the California Academy of Sciences, in a statement.
https://kra26c.cc
kraken сайт
“While it is critical to place protections on known threatened species, we must also allocate resources towards identifying unknown species that may be just as important to the functioning of an ecosystem,” Bennett said.
Researchers connected to the institution described 138 new species in 2024, including 32 fish. One standout was a pygmy pipehorse named Cylix nkosi. The seahorse relative was originally found in 2021 in the cool temperate waters surrounding the North Island of New Zealand, but the species described this year was discovered in the subtropical waters off South Africa, expanding the known range of this group to the Indian Ocean
“South African reefs present notoriously difficult diving conditions with rough weather and intense, choppy waves — we knew we only had one dive to find it,” underwater photographer and marine biologist Richard Smith said in a statement.
“This species is also quite cryptic, about the size of a golf tee, but luckily we spotted a female camouflaged against some sponges about a mile offshore on the sandy ocean floor.”
The researchers involved in describing the new species chose nkosi as its name. A reference to the local Zulu word for “chief,” the name reflects the species’ crown-like head shape and acknowledges South Africa’s KwaZulu-Natal province where it was found.
прокапаться от алкоголя цены прокапаться от алкоголя цены .
выведение из запоя на дому ростов на дону выведение из запоя на дому ростов на дону .
151 we’re okay, we’ve received any individual here now.
Casino Siteleri: Canl? Casino Siteleri – deneme bonusu veren casino siteleri
One other issue is when you are in a circumstances where you do not possess a co-signer then you may really need to try to make use of all of your federal funding options. You’ll find many grants or loans and other scholarships or grants that will supply you with funds that can help with classes expenses. Thank you for the post.
купить диплом об окончании
deneme bonusu veren casino siteleri: guvenilir casino siteleri – en guvenilir casino siteleri
As a result, many people across Mumbai have had to pay through teeth while purchasing forex in Mumbai.
If you’re too far from the telephone firm’s central office, a DSL connection won’t work as properly — if in any respect.