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 } }
This is a car identification quiz, taking in vehicles from many countries and certainly from many different periods in motoring.
trouver un mГ©dicament en pharmacie: kamagra livraison 24h – п»їpharmacie en ligne france
https://viagrameilleurprix.shop/# SildГ©nafil Teva 100 mg acheter
pharmacie en ligne livraison europe
pharmacie en ligne france fiable: pharmacie en ligne france – Pharmacie en ligne livraison Europe
Lucky Jet – твой шанс на большие выигрыши!
Попробуй захватывающую краш-игру прямо сейчас! Регистрируйся и получи бонус до 500% на первый депозит с промокодом: LuckyJetTeam.
bot lucky jet
Об игре
Lucky Jet — это не просто игра, а захватывающее приключение, в котором каждый момент может стать решающим! Эта краш-игра бросает вызов вашим инстинктам и способности быстро принимать решения. В основе игры — динамичная механика, где игроки ставят на рост коэффициента, но задача не в том, чтобы ждать до последнего, а вовремя вывести свой выигрыш, прежде чем персонаж взлетит слишком высоко и случится крах.
Чем выше коэффициент, тем более значительная награда! Но не забывайте: в этом азартном путешествии важен каждый момент, ведь именно ваше решение о выводе решит, насколько велик будет ваш выигрыш. Это не просто игра, а настоящее испытание на скорость и удачу! Простые правила, быстрые раунды и реальные выигрыши – вот почему игроки выбирают Lucky Jet.
Бонусы и промокоды в Lucky Jet
В Lucky Jet вас ждут щедрые бонусы и эксклюзивные промокоды, которые помогут увеличить ваш баланс и продлить удовольствие от игры! Мы ценим активных игроков и регулярно запускаем новые акции, чтобы сделать ваш игровой процесс еще выгоднее.
Актуальные бонусные предложения
Бонус 500% на первый депозит
Используйте промокод LuckyJetTeam при пополнении счета и получите увеличение депозита в 5 раз! Это отличная возможность начать игру с солидным запасом.
Еженедельные акции и фриспины
Чем больше вы играете, тем больше подарков получаете! Участвуйте в регулярных промо-акциях и получайте фриспины, бонусные деньги и дополнительные награды за активность.
Кэшбэк до 10%
Проиграли? Не беда! В Lucky Jet вы можете вернуть часть потерянных средств благодаря системе кэшбэка. Еженедельно вам будет начисляться до 10% возврата от проигранных ставок.
Следите за новыми акциями! Мы постоянно обновляем бонусные предложения, поэтому не упустите возможность воспользоваться самыми выгодными промо. Подписывайтесь на новости и следите за актуальными акциями, чтобы всегда быть в выигрыше!
Используйте бонусы и повышайте свои шансы на победу в Lucky Jet!
Как начать играть в Lucky Jet
Готовы испытать удачу и выиграть по-крупному? Следуйте этим простым шагам:
Зарегистрируйтесь на официальном сайте 1win. Процесс регистрации занимает всего пару минут.
Пополните счет удобным для вас способом: банковской картой, электронными кошельками или даже криптовалютой.
Откройте Lucky Jet в разделе казино и приготовьтесь к динамичному игровому процессу.
Сделайте ставку и следите за ростом коэффициента. Чем выше он поднимается – тем больше ваш потенциальный выигрыш.
Выведите выигрыш до того, как Lucky Jet взлетит! Главное – не жадничать и вовремя остановиться, иначе ставка сгорит.
Используйте стратегии, анализируйте предыдущие раунды и комбинируйте ставки, чтобы увеличить свои шансы на победу!
pharmacies en ligne certifiГ©es: kamagra livraison 24h – pharmacie en ligne sans ordonnance
Pharmacie Internationale en ligne: kamagra livraison 24h – acheter mГ©dicament en ligne sans ordonnance
Achat mГ©dicament en ligne fiable: pharmacie en ligne france – pharmacie en ligne sans ordonnance
Cute baby animals bring visitors to zoos and aquariums. What happens when they grow up?
арбитраж трафика с нуля
One of the best things that can happen to a zoo or aquarium is for one of their resident animals to go viral.
Just look at the multi-hour-long lines to see Moo Deng, a pygmy hippo in Thailand who has become an internet sensation following her July 2024 birth. The sassy animal is now a full-on brand, with Khao Kheow Open Zoo selling Moo Deng merchandise and even releasing a single “by” the hippo in multiple languages.
Meanwhile, Pesto — a baby king penguin who was eating more fish than his parents by the time he was a few weeks old — is also an online celebrity, with human stars like Olivia Rodrigo and Katy Perry stopping by to meet him.
But what happens when these cute animals become, well, less cute? The Sea Life Melbourne aquarium has already been planning for the next phase of Pesto’s life — and answering questions from the public about his changing appearance.
It’s normal for king penguins to lose their feathers by the time they’re about a year old and become confident swimmers. As a result, a spokesperson for the aquarium says, guests have started asking why Pesto looks different — or why they can’t find him at all.
“We are getting a few guests thinking we have moved him off display completely,” says the spokesperson. “Most of the team’s time is spent pointing him out to guests because he looks so different now.”
The bottom line is that cute baby animals make money.
Admission tickets are only the beginning. Many zoos and aquariums offer special “behind the scenes” or “zookeeper for a day” packages at much higher prices. At Sea Life Melbourne, standard entry tickets for adults start at $51, while the Penguin Passport — which include a 45-minute tour of the birds’ area and a look at how their food is prepared — is $199.
The real jackpot, though, is merchandise. Stuffed animals, T-shirts, fridge magnets, keychains, kids’ books and other branded products are a major way for zoos and aquariums to make money.
Pharmacie Internationale en ligne: pharmacie en ligne france pas cher – trouver un mГ©dicament en pharmacie
I have learned result-oriented things from the blog post. One other thing I have found is that usually, FSBO sellers will certainly reject a person. Remember, they would prefer never to use your products and services. But if an individual maintain a gradual, professional romance, offering help and being in contact for about four to five weeks, you will usually be capable to win interviews. From there, a house listing follows. Thanks a lot
Look of the Week: Kendrick Lamar’s Super Bowl pants signal the return of flares
Кракен даркнет
This year’s Super Bowl halftime show was hardly a fashion extravaganza, with headliner Kendrick Lamar keeping things simple in a backwards cap and motorbike-style varsity jacket, which he kept on throughout.
And without the costume-change roulette we’ve come to expect of halftime shows, the internet fixated on one item in particular: his jeans.
While not quite the bell-bottoms of decades past (the 1970s and the 2000s, specifically), the Compton-born rapper’s washed denim pants flared out at the knee and dragged beneath his heels along the stage at Caesars Superdrome in New Orleans. His silhouette stood in stark contrast to that of record producer Mustard, who made a brief cameo in a pair of outsized jeans straight from the West Coast hip-hop playbook.
Opinions were, as ever, divided on social media. Some users described Lamar’s flares as “women’s jeans” and “Hannah Montana pants,” earning him comparisons to everyone from Jennifer Aniston to country singer Lainey Wilson. Others joked that their moms were looking for a similar pair or that they nodded to millennials, for whom flares were a teenage staple.
But those suggesting his style was outdated, or gender-inappropriate, may not have been paying attention to the recent resurgence of flares — in both womenswear and menswear. After all, Lamar’s jeans were designed by one of the most influential figures in modern fashion, Celine’s former creative director Hedi Slimane, before he departed the French label in October.
Achat mГ©dicament en ligne fiable https://viagrameilleurprix.shop/# Viagra gГ©nГ©rique sans ordonnance en pharmacie
Scores of unexploded World War II bombs discovered under children’s playground
lucky jet сигналы
Scores of unexploded bombs dating from World War II have been recovered from a children’s playground in northern England after a chance discovery.
Local officials in the town of Wooler, Northumberland called in bomb disposal experts after workers involved in a planned overhaul of Scotts Play Park found unexploded ordnance, the parish council said in a statement sent to CNN on Monday.
Two bombs were initially removed by the British Army, the UK Ministry of Defense said in a statement. The parish council was then advised that a full survey of the area was required, according to a council spokesperson.
Bomb disposal company Brimstone Site Investigation then uncovered 65 10-pound practice bombs and smoke cartridges on the first day of works, with a further 90 practice bombs recovered on the second day.
The company told CNN that the bombs date from World War II.
According to the parish council, all of the bombs need to be found and removed before the park can be reopened. It said 174 devices had been found so far.
pharmacie en ligne france livraison belgique Achat mГ©dicament en ligne fiable pharmacie en ligne livraison europe
pharmacie en ligne sans ordonnance https://viagrameilleurprix.shop/# Viagra homme prix en pharmacie sans ordonnance
pharmacie en ligne https://viagrameilleurprix.com/# Viagra femme sans ordonnance 24h
Excellent post. I was checking continuously this blog and I’m inspired! Very useful info specifically the last part 🙂 I take care of such information much. I used to be seeking this particular information for a very lengthy time. Thank you and good luck.
Lucky Jet – твой шанс на большие выигрыши!
Попробуй захватывающую краш-игру прямо сейчас! Регистрируйся и получи бонус до 500% на первый депозит с промокодом: LuckyJetTeam.
lucky jet игра
Об игре
Lucky Jet — это не просто игра, а захватывающее приключение, в котором каждый момент может стать решающим! Эта краш-игра бросает вызов вашим инстинктам и способности быстро принимать решения. В основе игры — динамичная механика, где игроки ставят на рост коэффициента, но задача не в том, чтобы ждать до последнего, а вовремя вывести свой выигрыш, прежде чем персонаж взлетит слишком высоко и случится крах.
Чем выше коэффициент, тем более значительная награда! Но не забывайте: в этом азартном путешествии важен каждый момент, ведь именно ваше решение о выводе решит, насколько велик будет ваш выигрыш. Это не просто игра, а настоящее испытание на скорость и удачу! Простые правила, быстрые раунды и реальные выигрыши – вот почему игроки выбирают Lucky Jet.
Бонусы и промокоды в Lucky Jet
В Lucky Jet вас ждут щедрые бонусы и эксклюзивные промокоды, которые помогут увеличить ваш баланс и продлить удовольствие от игры! Мы ценим активных игроков и регулярно запускаем новые акции, чтобы сделать ваш игровой процесс еще выгоднее.
Актуальные бонусные предложения
Бонус 500% на первый депозит
Используйте промокод LuckyJetTeam при пополнении счета и получите увеличение депозита в 5 раз! Это отличная возможность начать игру с солидным запасом.
Еженедельные акции и фриспины
Чем больше вы играете, тем больше подарков получаете! Участвуйте в регулярных промо-акциях и получайте фриспины, бонусные деньги и дополнительные награды за активность.
Кэшбэк до 10%
Проиграли? Не беда! В Lucky Jet вы можете вернуть часть потерянных средств благодаря системе кэшбэка. Еженедельно вам будет начисляться до 10% возврата от проигранных ставок.
Следите за новыми акциями! Мы постоянно обновляем бонусные предложения, поэтому не упустите возможность воспользоваться самыми выгодными промо. Подписывайтесь на новости и следите за актуальными акциями, чтобы всегда быть в выигрыше!
Используйте бонусы и повышайте свои шансы на победу в Lucky Jet!
Как начать играть в Lucky Jet
Готовы испытать удачу и выиграть по-крупному? Следуйте этим простым шагам:
Зарегистрируйтесь на официальном сайте 1win. Процесс регистрации занимает всего пару минут.
Пополните счет удобным для вас способом: банковской картой, электронными кошельками или даже криптовалютой.
Откройте Lucky Jet в разделе казино и приготовьтесь к динамичному игровому процессу.
Сделайте ставку и следите за ростом коэффициента. Чем выше он поднимается – тем больше ваш потенциальный выигрыш.
Выведите выигрыш до того, как Lucky Jet взлетит! Главное – не жадничать и вовремя остановиться, иначе ставка сгорит.
Используйте стратегии, анализируйте предыдущие раунды и комбинируйте ставки, чтобы увеличить свои шансы на победу!
pharmacies en ligne certifiГ©es: Acheter Cialis – pharmacie en ligne france livraison belgique
Pharmacie sans ordonnance Acheter Cialis pharmacie en ligne sans ordonnance
Thank you for this article. I will also like to mention that it can end up being hard if you find yourself in school and simply starting out to initiate a long history of credit. There are many pupils who are merely trying to make it and have a long or beneficial credit history is often a difficult thing to have.
Viagra prix pharmacie paris: viagra en ligne – Viagra homme sans prescription
Do you have a spam issue on this blog; I also am a blogger, and I was wanting to know your situation; we have created some nice methods and we are looking to trade techniques with others, please shoot me an e-mail if interested.
I will also like to express that most people that find themselves without the need of health insurance usually are students, self-employed and people who are not working. More than half with the uninsured are really under the age of 35. They do not experience they are wanting health insurance as they are young along with healthy. The income is normally spent on housing, food, in addition to entertainment. Some people that do represent the working class either complete or not professional are not presented insurance by their work so they go without with the rising tariff of health insurance in the usa. Thanks for the suggestions you share through this web site.
I have realized that over the course of developing a relationship with real estate managers, you’ll be able to get them to understand that, in most real estate financial transaction, a commission rate is paid. Ultimately, FSBO sellers do not “save” the commission payment. Rather, they try to earn the commission by simply doing a agent’s work. In accomplishing this, they expend their money in addition to time to carry out, as best they are able to, the responsibilities of an realtor. Those assignments include uncovering the home by means of marketing, representing the home to willing buyers, building a sense of buyer urgency in order to prompt an offer, booking home inspections, handling qualification check ups with the bank, supervising fixes, and assisting the closing of the deal.
Certain kinds of debt (mortgages, pupil loans, etc.) can truly be good within the sense that they help you build your credit score.
After I originally commented I clicked the -Notify me when new feedback are added- checkbox and now every time a comment is added I get 4 emails with the same comment. Is there any manner you’ll be able to remove me from that service? Thanks!
https://pharmaciemeilleurprix.shop/# Pharmacie sans ordonnance
pharmacie en ligne fiable
hello!,I like your writing very much! share we communicate more about your post on AOL? I require a specialist on this area to solve my problem. May be that’s you! Looking forward to see you.