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 } }
kamagra pas cher achat kamagra kamagra gel
pharmacie en ligne fiable: Meilleure pharmacie en ligne – pharmacie en ligne france pas cher pharmafst.com
One thing I’d really like to say is always that car insurance canceling is a dreadful experience and if you’re doing the appropriate things being a driver you simply will not get one. Lots of people do obtain the notice that they have been officially dropped by their particular insurance company and many have to scramble to get supplemental insurance following a cancellation. Inexpensive auto insurance rates are frequently hard to get from a cancellation. Understanding the main reasons pertaining to auto insurance cancelling can help owners prevent losing one of the most significant privileges offered. Thanks for the concepts shared by means of your blog.
Achetez vos kamagra medicaments: Kamagra pharmacie en ligne – Acheter Kamagra site fiable
A powerful share, I simply given this onto a colleague who was doing a little evaluation on this. And he actually bought me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to debate this, I feel strongly about it and love studying extra on this topic. If attainable, as you grow to be experience, would you thoughts updating your weblog with extra details? It’s extremely helpful for me. Big thumb up for this blog put up!
Thanks for the tips about credit repair on your blog. Some tips i would offer as advice to people is always to give up the mentality they can buy currently and pay later. Like a society most people tend to make this happen for many issues. This includes vacation trips, furniture, in addition to items we wish. However, you’ll want to separate a person’s wants from the needs. If you are working to improve your credit rating score actually you need some trade-offs. For example you possibly can shop online to save money or you can go to second hand merchants instead of costly department stores regarding clothing.
смотреть фильмы без рекламы лучшие фильмы 2025 года в HD
смотреть фильмы бесплатно фильмы 2025 без регистрации и рекламы
фильмы онлайн русском языке смотреть фильмы онлайн бесплатно 2025
Many thanks for your post. I’d like to say that the tariff of car insurance differs from one coverage to another, simply because there are so many different facets which contribute to the overall cost. For instance, the brand name of the automobile will have a massive bearing on the price. A reliable outdated family auto will have a more affordable premium than the usual flashy performance car.
фильмы комедии 2025 боевики 2025 смотреть бесплатно HD
фильмы 2025 уже вышедшие фильмы 2025 без регистрации и рекламы
фильмы 2025 года уже вышедшие смотреть фильмы онлайн бесплатно 2025
Thanks for revealing your ideas. I might also like to express that video games have been ever before evolving. Technology advances and revolutions have aided create genuine and interactive games. Most of these entertainment video games were not as sensible when the real concept was first of all being tried out. Just like other areas of technology, video games also have had to grow through many many years. This is testimony for the fast growth and development of video games.
Thanks for this article. I would also like to convey that it can be hard if you are in school and just starting out to create a long credit history. There are many scholars who are only trying to live and have a protracted or beneficial credit history are often a difficult thing to have.
Usually I don’t learn article on blogs, however I wish to say that this write-up very compelled me to take a look at and do so! Your writing taste has been surprised me. Thank you, quite great post.
https://kamagraprix.shop/# Achetez vos kamagra medicaments
Mist and microlightning
solflare
To recreate a scenario that may have produced Earth’s first organic molecules, researchers built upon experiments from 1953 when American chemists Stanley Miller and Harold Urey concocted a gas mixture mimicking the atmosphere of ancient Earth. Miller and Urey combined ammonia (NH3), methane (CH4), hydrogen (H2) and water, enclosed their “atmosphere” inside a glass sphere and jolted it with electricity, producing simple amino acids containing carbon and nitrogen. The Miller-Urey experiment, as it is now known, supported the scientific theory of abiogenesis: that life could emerge from nonliving molecules.
For the new study, scientists revisited the 1953 experiments but directed their attention toward electrical activity on a smaller scale, said senior study author Dr. Richard Zare, the Marguerite Blake Wilbur Professor of Natural Science and professor of chemistry at Stanford University in California. Zare and his colleagues looked at electricity exchange between charged water droplets measuring between 1 micron and 20 microns in diameter. (The width of a human hair is 100 microns.)
“The big droplets are positively charged. The little droplets are negatively charged,” Zare told CNN. “When droplets that have opposite charges are close together, electrons can jump from the negatively charged droplet to the positively charged droplet.”
The researchers mixed ammonia, carbon dioxide, methane and nitrogen in a glass bulb, then sprayed the gases with water mist, using a high-speed camera to capture faint flashes of microlightning in the vapor. When they examined the bulb’s contents, they found organic molecules with carbon-nitrogen bonds. These included the amino acid glycine and uracil, a nucleotide base in RNA.
“We discovered no new chemistry; we have actually reproduced all the chemistry that Miller and Urey did in 1953,” Zare said. Nor did the team discover new physics, he added — the experiments were based on known principles of electrostatics.
“What we have done, for the first time, is we have seen that little droplets, when they’re formed from water, actually emit light and get this spark,” Zare said. “That’s new. And that spark causes all types of chemical transformations.”
“You have a government that is reckless about what is going to happen to Guyana,” said Melinda Janki, an international lawyer in Guyana who is handling several lawsuits against Exxon. It’s pursuing “a supposed course of development that is actually backward and destructive,” she told CNN.
kelpdao
And while plenty of Guyanese people welcome the new oil industry, some say Guyana’s startling economic statistics do not reflect a real-world prosperity for ordinary people, many of whom are struggling with the higher prices accompanying the oil boom. Inflation rose 6.6% in 2023, with prices of some foods shooting up much more rapidly.
“Since the oil extraction began in Guyana, we have noticed that our cost of living has gone sky high,” said Wintress White, of Red Thread, a non-profit that focuses on improving living conditions for Guyanese women. “The money is not trickling down to the masses,” she told CNN.
CNN contacted President Ali, the Ministry of Natural Resources and the Ministry of Finance for comment but received no response.
Guyana, a former Dutch then British colony which gained independence in 1966, is one of only a handful of countries that is a “carbon sink,” meaning it stores more planet-heating pollution than it produces. This is due to its vast rainforest; trees remove carbon dioxide from the atmosphere as they grow.
The country has protected its biodiversity where others have destroyed theirs, President Ali said in a BBC interview last year. In 2009, the country signed an agreement with Norway, which promised Guyana more than $250 million to preserve its 18.5 million hectares, or nearly 46 million acres, of forests.
Ali insists the country can balance climate leadership and fossil fuel exploitation. The new oil wealth will allow Guayana to develop, including building climate adaptations such as sea walls, he has said. He has also pointed to the continued failures of wealthy countries, already grown rich on their own fossil fuels, to help poorer countries with climate finance.
But there are concerns Guyana could fall victim to the “resource curse,” in which vast, new wealth ?can actually make life worse for those who live there.
A tiny rainforest country is growing into a petrostate. A US oil company could reap the biggest rewards
swell network
Guyana’s destiny changed in 2015. US fossil fuel giant Exxon discovered nearly 11 billion barrels of oil in the deep water off the coast of this tiny, rainforested country.
It was one of the most spectacular oil discoveries of recent decades. By 2019, Exxon and its partners, US oil company Hess and China-headquartered CNOOC, had started producing the fossil fuel.? They now pump around 650,000 barrels of oil a day, with plans to more than double this to 1.3 million by 2027.
Guyana now has the world’s highest expected oil production growth through 2035.
This country — sandwiched between Brazil, Venezuela and Suriname — has been hailed as a climate champion for the lush, well-preserved forests that carpet nearly 90% of its land. It is on the path to becoming a petrostate at the same time as the impacts of the fossil fuel-driven climate crisis escalate.
While the government says environmental protection and an oil industry can go hand-in-hand, and low-income countries must be allowed to exploit their own resources, critics say it’s a dangerous path in a warming world, and the benefits may ultimately skew toward Exxon — not Guyana.
фильм драма детектив сериалы 2025 онлайн бесплатно HD
смотреть фильмы онлайн 2025 ужасы 2025 смотреть онлайн HD
Woah! I’m really digging the template/theme of this site. It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between user friendliness and visual appeal. I must say you have done a awesome job with this. Additionally, the blog loads very fast for me on Safari. Excellent Blog!
Something more important is that when searching for a good on the net electronics shop, look for online shops that are consistently updated, maintaining up-to-date with the most current products, the most effective deals, along with helpful information on services. This will make sure that you are doing business with a shop which stays atop the competition and gives you what you need to make intelligent, well-informed electronics purchases. Thanks for the essential tips I’ve learned through your blog.
This is very fascinating, You’re an excessively skilled blogger. I have joined your rss feed and stay up for searching for extra of your magnificent post. Also, I have shared your site in my social networks!
https://pharmafst.com/# pharmacie en ligne france fiable
Scientists redid an experiment that showed how life on Earth could have started. They found a new possibility
safepal
In the 1931 movie “Frankenstein,” Dr. Henry Frankenstein howling his triumph was an electrifying moment in more ways than one. As massive bolts of lightning and energy crackled, Frankenstein’s monster stirred on a laboratory table, its corpse brought to life by the power of electricity.
Electrical energy may also have sparked the beginnings of life on Earth billions of years ago, though with a bit less scenery-chewing than that classic film scene.
Earth is around 4.5 billion years old, and the oldest direct fossil evidence of ancient life — stromatolites, or microscopic organisms preserved in layers known as microbial mats — is about 3.5 billion years old. However, some scientists suspect life originated even earlier, emerging from accumulated organic molecules in primitive bodies of water, a mixture sometimes referred to as primordial soup.
But where did that organic material come from in the first place? Researchers decades ago proposed that lightning caused chemical reactions in ancient Earth’s oceans and spontaneously produced the organic molecules.
Now, new research published March 14 in the journal Science Advances suggests that fizzes of barely visible “microlightning,” generated between charged droplets of water mist, could have been potent enough to cook up amino acids from inorganic material. Amino acids — organic molecules that combine to form proteins — are life’s most basic building blocks and would have been the first step toward the evolution of life.
acheter kamagra site fiable kamagra gel acheter kamagra site fiable
kamagra 100mg prix: acheter kamagra site fiable – kamagra oral jelly
vente de mГ©dicament en ligne: Medicaments en ligne livres en 24h – pharmacie en ligne pharmafst.com