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 } }
F*ckin? remarkable issues here. I?m very glad to peer your post. Thanks a lot and i am looking forward to touch you. Will you please drop me a mail?
I’m not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come back in the future. Cheers
I liked up to you will receive performed right here. The comic strip is tasteful, your authored material stylish. however, you command get bought an edginess over that you want be turning in the following. in poor health definitely come more beforehand again as exactly the similar nearly very ceaselessly inside case you shield this increase.
It is best to take part in a contest for the most effective blogs on the web. I will advocate this website!
Excellent weblog right here! Also your web site rather a lot up very fast! What host are you the use of? Can I am getting your affiliate hyperlink in your host? I desire my web site loaded up as fast as yours lol
Thanks for your publication. I would also love to opinion that the very first thing you will need to accomplish is determine if you really need credit improvement. To do that you will have to get your hands on a replica of your credit profile. That should really not be difficult, because the government necessitates that you are allowed to acquire one absolutely free copy of the credit report each year. You just have to request the right persons. You can either read the website for your Federal Trade Commission or even contact one of the major credit agencies directly.
My brother recommended I might like this website. He was entirely right. This post truly made my day. You cann’t imagine simply how much time I had spent for this information! Thanks!
I have figured out some new items from your web page about personal computers. Another thing I’ve always thought is that computer systems have become a specific thing that each family must have for some reasons. They supply you with convenient ways in which to organize the home, pay bills, search for information, study, listen to music and in many cases watch television shows. An innovative way to complete these tasks is to use a laptop. These desktops are mobile, small, robust and portable.
Hey! Do you know if they make any plugins to help with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results. If you know of any please share. Appreciate it!
I just couldn’t depart your web site prior to suggesting that I extremely enjoyed the standard info a person provide for your visitors? Is going to be back often to check up on new posts
I’m often to blogging and i really recognize your content. The article has really peaks my interest. I am going to bookmark your website and hold checking for brand spanking new information.
It is my belief that mesothelioma is definitely the most lethal cancer. It contains unusual features. The more I look at it the greater I am sure it does not act like a true solid tissue cancer. In the event that mesothelioma is a rogue viral infection, therefore there is the chance for developing a vaccine as well as offering vaccination to asbestos subjected people who are really at high risk connected with developing long term asbestos related malignancies. Thanks for sharing your ideas for this important health issue.
After study a couple of of the blog posts on your web site now, and I truly like your manner of blogging. I bookmarked it to my bookmark web site listing and can be checking again soon. Pls try my web page as nicely and let me know what you think.
Hi there! I’m at work surfing around your blog from my new apple iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the fantastic work!
All these claiming and filing is a part of the legal procedure and a complicated process, which is better to be done by the professional in this field.
The past three years have been a trying time for a notable portion of the United States citizenry.
The hostess may change up the game by playing “four corners” (the first player to mark all four corners of the game card wins) or “fill up” (players must mark every square on the card).
By elevating the mood of those around you, you can reduce their particular anxiety levels, and possibly improve the quality of social interaction you have with them, lowering your anxiety level even more and having work far more enjoyable.
My brother recommended I might like this website. He was entirely right. This post actually made my day. You can not imagine just how much time I had spent for this info! Thanks!
This way, you will be able to boost your income.
Since we are dealing with investments & money, it would be wise to consider a good financial planner or consultant who can throw some light to your portfolio & balance out the investment risk during the bear market.
You buy the right to honors the contract for a price called premium.
Stock market delivery is squaring off positions on the same day as intraday, then what is intraday?
Some people choose to pay the interest during those times even though they’re waiting until they’re out of school to start repaying the loan’s principal.
But, it is this misconception that often makes people’s hard-earned money go to drains.
Customer loyalty and referral programs are ways to create creative customer experiences.
So, when the username and password are inserted in the phishing sites, the information is captured by the hackers who then use it for accessing the crypto accounts of traders.
In 1958, shareholders voted to alter its legal kind from a joint inventory firm to a mutual organization, making the company privately owned by its policyholders.
Hi there, I found your site via Google whilst searching for a similar subject, your website came up, it seems good. I have bookmarked it in my google bookmarks.
The second higher mountain space (a lot lower than the Alps) is situated in the north.