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 } }
My web blog … Daycares popular listings (Damon)
You made some decent factors there. I regarded on the internet for the issue and found most individuals will associate with together with your website.
I am usually to running a blog and i really admire your content. The article has really peaks my interest. I’m going to bookmark your website and hold checking for brand spanking new information.
hi!,I love your writing very much! proportion we be in contact more approximately your post on AOL? I need an expert on this house to solve my problem. Maybe that’s you! Looking ahead to look you.
Great write-up, I?m normal visitor of one?s site, maintain up the excellent operate, and It is going to be a regular visitor for a long time.
Youre so cool! I dont suppose Ive read anything like this before. So good to seek out somebody with some original ideas on this subject. realy thanks for beginning this up. this web site is something that’s wanted on the net, somebody with a little originality. useful job for bringing one thing new to the internet!
Thanks for your article on this site. From my very own experience, often times softening upwards a photograph could provide the wedding photographer with a bit of an imaginative flare. Oftentimes however, the soft clouds isn’t precisely what you had planned and can quite often spoil an otherwise good photograph, especially if you consider enlarging this.
Carew, Sinead (November 13, 2008).
Thanks for your intriguing article. Other thing is that mesothelioma is generally brought on by the inhalation of materials from mesothelioma, which is a dangerous material. It can be commonly seen among laborers in the construction industry that have long contact with asbestos. It can be caused by moving into asbestos covered buildings for years of time, Your age plays an important role, and some people are more vulnerable to the risk when compared with others.
Make it clear for your clients.
Hi just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same results.
Normally I don’t read post on blogs, however I would like to say that this write-up very pressured me to try and do it! Your writing style has been surprised me. Thanks, very nice article.
In my opinion that a foreclosed can have a significant effect on the debtor’s life. Real estate foreclosures can have a Several to few years negative affect on a client’s credit report. A new borrower who has applied for a mortgage or just about any loans for example, knows that the actual worse credit rating is actually, the more tricky it is for any decent bank loan. In addition, it can affect the borrower’s capability to find a decent place to lease or rent, if that becomes the alternative houses solution. Great blog post.
Attractive section of content. I just stumbled upon your site and in accession capital to assert that I get actually enjoyed account your blog posts. Anyway I?ll be subscribing to your augment and even I achievement you access consistently quickly.
Securities and Exchange Commission (SEC) to list companies.
Здравствуйте!
Приобрести документ о получении высшего образования можно у нас в столице.
cars.teamforum.ru/viewtopic.php?f=2&t=1602
For a high volume of goods to be shipped and purchased by the credit rich consumer, loose regulations and increased truck capacity allowed.
I just couldn’t depart your website prior to suggesting that I extremely enjoyed the standard info a person provide for your visitors? Is going to be back often in order to check up on new posts
I have mastered some new elements from your website about pcs. Another thing I have always presumed is that computers have become a product that each residence must have for several reasons. They supply you with convenient ways to organize the home, pay bills, search for information, study, focus on music and even watch tv shows. An innovative technique to complete these types of tasks is a notebook. These personal computers are mobile, small, highly effective and transportable.
I just couldn’t depart your website prior to suggesting that I extremely loved the usual information an individual provide on your guests? Is going to be again ceaselessly to check out new posts
Howdy are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and create my own. Do you need any coding expertise to make your own blog? Any help would be greatly appreciated!
Howdy! I know this is kinda off topic however I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa? My site discusses a lot of the same subjects as yours and I believe we could greatly benefit from each other. If you are interested feel free to shoot me an e-mail. I look forward to hearing from you! Fantastic blog by the way!
Thanks for this glorious article. Yet another thing to mention is that nearly all digital cameras arrive equipped with some sort of zoom lens that allows more or less of any scene being included by way of ‘zooming’ in and out. These kind of changes in {focus|focusing|concentration|target|the a**** length are generally reflected in the viewfinder and on significant display screen right on the back of this camera.
After examine just a few of the blog posts on your web site now, and I actually like your approach of blogging. I bookmarked it to my bookmark website record and shall be checking back soon. Pls take a look at my site as nicely and let me know what you think.
Привет, друзья!
Покупка диплома о среднем полном образовании: как избежать мошенничества?
promocodser.ru/students/educational-resources
wonderful points altogether, you just gained a brand new reader. What would you suggest about your post that you made some days ago? Any positive?
Itano, Nicole (14 Might 2009).
It?s laborious to search out knowledgeable individuals on this topic, however you sound like you know what you?re speaking about! Thanks
F*ckin? tremendous things here. I am very glad to see your article. Thanks a lot and i am looking forward to contact you. Will you kindly drop me a mail?
You can definitely see your skills in the work you write. The arena hopes for even more passionate writers like you who aren’t afraid to say how they believe. At all times go after your heart.