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 } }
I would like to add if you do not actually have an insurance policy otherwise you do not remain in any group insurance, you may well gain from seeking the aid of a health agent. Self-employed or those with medical conditions typically seek the help of an health insurance brokerage. Thanks for your short article.
In 1986, IDS acquired Wisconsin Employers Casualty Firm of Inexperienced Bay, Wisconsin and renamed it IDS Property Casualty Insurance Company.
продвижение сайта в топ москва продвижение сайта в топ москва .
If you are looking for the best money exchange rates, then here are a few tips that can help you make the best decision.
Luxury brands – Louis Vuitton and Frette are also heading towards India with the basic purpose of converting India into a manufacturing base for their products.
They may not give the attention and care you give your child as a single parent.
Valuable information. Lucky me I found your site by accident, and I am shocked why this accident didn’t happened earlier! I bookmarked it.
I?m now not sure the place you are getting your info, but great topic. I must spend a while learning more or figuring out more. Thank you for great information I used to be searching for this information for my mission.
To explain this further, a proposal could have a negative impact from the Discounted Cash Flow analysis, but if it is strategically beneficial to the company this decision will be accepted by the financial managers over a decision which has a positive impact on the Discounted Cash Flow analysis but is not strategically beneficial.
This concept, also called “stock for services” and sometimes “equity compensation” or “sweat equity,” can also be seen when startup companies use their shares of stock to entice service providers to provide necessary corporate services in exchange for a discount or for deferring service fees until a later date; see, e.g., “Idea Makers and Idea Brokers in High Technology Entrepreneurship” by Todd L. Juneau et al., Greenwood Press, 2003, which describes equity for service programs involving patent lawyers and securities lawyers who specialize in start-up companies as clients.
Wow! This blog looks exactly like my old one! It’s on a totally different subject but it has pretty much the same layout and design. Excellent choice of colors!
Woah! I’m really enjoying the template/theme of this site. It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a superb job with this. Also, the blog loads super quick for me on Safari. Superb Blog!
Привет, друзья!
Мы можем предложить дипломы психологов, юристов, экономистов и любых других профессий по разумным тарифам.
vitz.ru/forums/index.php?autocom=gallery&req=si&img=2120&st=0&
Hey There. I found your blog using msn. This is a really well written article. I?ll make sure to bookmark it and return to read more of your useful information. Thanks for the post. I will definitely return.
mexican pharmacy: purple pharmacy mexico price list – best online pharmacies in mexico
Valuable info. Lucky me I found your site by accident, and I’m shocked why this accident didn’t happened earlier! I bookmarked it.
mexico drug stores pharmacies: mexico pharmacies prescription drugs – buying from online mexican pharmacy
Whats up are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you need any coding knowledge to make your own blog? Any help would be really appreciated!
reliable canadian pharmacy: canadian online pharmacy reviews – precription drugs from canada
Useful info. Lucky me I found your website by accident, and I am stunned why this coincidence did not happened in advance! I bookmarked it.
medication canadian pharmacy: canadian pharmacy 1 internet online drugstore – pet meds without vet prescription canada
Thanks for your submission. I would also like to say that the first thing you will need to complete is to see if you really need credit score improvement. To do that you will need to get your hands on a replica of your credit report. That should really not be difficult, because government necessitates that you are allowed to have one absolutely free copy of your own credit report yearly. You just have to request that from the right individuals. You can either look at website for your Federal Trade Commission or maybe contact one of the leading credit agencies specifically.
Привет!
Полезные советы по безопасной покупке диплома о высшем образовании
seozalex.ru/2009/05/26/sapient-social-submitter-rabotaet/index
21 December 2013 – A invoice on the only Property Tax and the auction of homes is accepted by a majority of 152 deputies within the 300-seat chamber.
What Are the most important Drawbacks of Living in a Tiny House?
A best stock market advisory service executes the transactions in the most effective and efficient manner and the traders are at ease without having to worry about anything.
I have noticed that in cameras, special receptors help to {focus|concentrate|maintain focus|target|a**** automatically. The sensors associated with some surveillance cameras change in contrast, while others work with a beam associated with infra-red (IR) light, specifically in low lighting. Higher specification cameras sometimes use a mix of both programs and may have Face Priority AF where the digicam can ‘See’ any face as you concentrate only upon that. Thank you for sharing your opinions on this site.
Visit my web blog – Daycares By Category
If you are looking to add more to your investment portfolio, other stocks such as LPHI should be a good option.
Thanks for your post. My spouse and i have always noticed that a majority of people are desirous to lose weight when they wish to show up slim and attractive. Nonetheless, they do not continually realize that there are additional benefits for you to losing weight also. Doctors state that overweight people have problems with a variety of conditions that can be perfectely attributed to the excess weight. The great thing is that people who are overweight in addition to suffering from several diseases can reduce the severity of their illnesses through losing weight. You’ll be able to see a steady but noted improvement with health as soon as even a moderate amount of weight loss is obtained.