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 actually make it seem so easy along with your presentation but I find this topic to be actually one thing that I feel I might by no means understand. It kind of feels too complicated and very wide for me. I’m having a look ahead to your subsequent post, I will attempt to get the grasp of it!
The report cited the Flood Control Act of 1965; legislation which was enacted in response to losses exceeding $1 billion (including a number of levee failures) throughout Hurricane Betsy.
Хочу поделиться опытом покупки в одном интернет-магазине сантехники. Решил обновить ванную комнату и искал место, где можно найти широкий выбор раковин и ванн. Этот магазин приятно удивил своим ассортиментом и сервисом. Там есть всё: от классических чугунных ванн до современных акриловых моделей.
Если вам нужна раковина в ванную комнату купить , то это точно туда. Цены конкурентные, а качество товаров подтверждено сертификатами. Консультанты помогли с выбором, ответили на все вопросы. Доставка пришла вовремя, и установка прошла без проблем. Остался очень доволен покупкой и сервисом.
In late 2011 they left Morgan Stanley to set up ICONIQ Capital to serve as independent wealth advisors to their clients with more autonomy.
I think one of your ads caused my browser to resize, you may well want to put that on your blacklist.
Air Florida additionally served Belize Metropolis, Belize; Charleston, South Carolina; Chicago (Midway Airport), Illinois; Dallas/Ft.
Great site! I recommend it to everyone!tarjima kino
Профессиональный сервисный центр по ремонту компьютерных блоков питания в Москве.
Мы предлагаем: ремонт блока питания цена
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Профессиональный сервисный центр по ремонту компьютероной техники в Москве.
Мы предлагаем: ремонт компьютеров центр
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
The 1963 Riviera surely must have turned some heads in Dearborn, but Ford looked particularly hard at the first Oldsmobile Toronado, long before it ever appeared in showrooms.
One of these is desktop search; users will probably be able to change the default desktop search program to one provided by a third get together instead of the Microsoft desktop search program that comes with Windows Vista, and desktop search packages will have the ability to seamlessly tie of their services into the working system.
Hi there, simply turned into aware of your weblog through Google, and found that it is really informative. I am gonna watch out for brussels. I will be grateful if you happen to continue this in future. Lots of other folks can be benefited out of your writing. Cheers!
Cenovus Power (March 15, 2019).
Look at my site: highstakes online
<a href=”https://remont-kondicionerov-wik.ru”>ремонт кондиционеров на дому в москве</a>
Jesse Livermore made hundreds of millions trading the stock market.
Excellent read, I just passed this onto a friend who was doing a little research on that. And he actually bought me lunch as I found it for him smile Therefore let me rephrase that: Thank you for lunch!
At the outset, every piece of Easy Soft software captures case data-one time only.
This would cover costs if a dog, for instance, was hit in a car accident, ingested a foreign item or was poisoned (the accident part), but also covers illnesses like cancer and infections.
сервис профи самара
Building shed a complete of 385,000 jobs from July 1981 through December 1982.
Thanks for revealing your ideas on this blog. Furthermore, a misconception regarding the lenders intentions if talking about foreclosure is that the standard bank will not getreceive my repayments. There is a certain amount of time the bank will require payments every now and then. If you are way too deep within the hole, they may commonly require that you pay the payment completely. However, i am not saying that they will not take any sort of payments at all. Should you and the lender can find a way to work one thing out, the actual foreclosure course of action may cease. However, if you continue to miss out on payments underneath the new system, the foreclosure process can pick up from where it left off.
Forex trading the over the counter currency markets offers an opportunity to prevaricate stock indexes and bond investing, but actually is more of a traded market following the ebbs and flows of international trade than it is an investment arena to plan retirement from.
I love your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to create my own blog and would like to find out where u got this from. thanks
This content has be en writt en with the help of GSA Content Generator Dem over sion!
Если у вас сломался телефон, советую этот сервисный центр. Я сам там чинил свой смартфон и остался очень доволен. Отличное обслуживание и разумные цены. Подробнее можно узнать здесь: ближайший ремонт телефон.
Feel free to visit my homepage … Daycares popular listings
(huberworld.de)
<a href=”https://remont-kondicionerov-wik.ru”>ремонт кондиционеров в москве</a>
Before choosing an asset that will be the most suitable for you there is also a very important thing to put in mind, to choose the exact time for every asset, in case to gain your advantage in trading.