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 } }
Its such as you learn my mind! You appear to know a lot about this, like you wrote the e book in it or something. I believe that you simply could do with a few percent to power the message house a bit, however other than that, this is magnificent blog. A fantastic read. I’ll certainly be back.
Thanks , I’ve recently been searching for information about this subject for ages and yours is the best I have discovered till now. But, what about the bottom line? Are you sure about the source?
I am curious to find out what blog platform you’re utilizing? I’m having some minor security issues with my latest site and I would like to find something more secure. Do you have any solutions?
WONDERFUL Post.thanks for share..more wait .. ?
Официальная покупка диплома вуза с сокращенной программой в Москве
Реально ли приобрести диплом стоматолога? Основные этапы
It is truly a great and useful piece of information. I am glad that you simply shared this useful information with us. Please stay us up to date like this. Thanks for sharing.
Процесс получения диплома стоматолога: реально ли это сделать быстро?
Oh my goodness! an amazing article dude. Thanks However I’m experiencing concern with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting similar rss drawback? Anyone who knows kindly respond. Thnkx
Hi! I’ve been reading your web site for a while now and finally got the courage to go ahead and give you a shout out from Lubbock Tx! Just wanted to say keep up the excellent job!
Процесс получения диплома стоматолога: реально ли это сделать быстро?
Thanks for this article. I’d personally also like to state that it can end up being hard when you are in school and just starting out to establish a long credit ranking. There are many students who are simply trying to make it and have long or good credit history can be a difficult factor to have.
okmark your blog and check again here regularly. I’m quite certain I will learn plenty of new stuff right here! Best of luck for the next!
Excellent post. I was checking continuously this blog and I’m impressed! Extremely helpful information particularly the last part 🙂 I care for such information a lot. I was looking for this particular info for a very long time. Thank you and good luck.
Useful information. Lucky me I found your site accidentally, and I am surprised why this accident did not happened earlier! I bookmarked it.
https://indianpharmacyeasy.com/# online pharmacy india
Pretty great post. I just stumbled upon your weblog and wanted to say that I’ve really enjoyed surfing around your weblog posts. After all I will be subscribing to your rss feed and I’m hoping you write once more soon!
Thanks for your write-up. One other thing is individual American states have their unique laws which affect home owners, which makes it quite hard for the Congress to come up with a new set of recommendations concerning home foreclosure on home owners. The problem is that a state features own laws and regulations which may have impact in an adverse manner on the subject of foreclosure insurance policies.
Interesting blog post. Some tips i would like to bring about is that computer system memory ought to be purchased if your computer can’t cope with whatever you do along with it. One can install two RAM boards containing 1GB each, for instance, but not one of 1GB and one with 2GB. One should make sure the manufacturer’s documentation for own PC to be certain what type of storage is required.
I think other web-site proprietors should take this site as an model, very clean and excellent user friendly style and design, let alone the content. You are an expert in this topic!
Do you have a spam problem on this website; I also am a blogger, and I was curious about your situation; many of us have developed some nice practices and we are looking to trade strategies with other folks, please shoot me an e-mail if interested.
hello!,I like your writing very much! share we communicate more about your post on AOL? I require a specialist on this area to solve my problem. May be that’s you! Looking forward to see you.
Сервисный центр предлагает замена вспышки olympus sp-570 замена матрицы olympus sp-570
I’m not sure exactly why but this web site is loading extremely slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later and see if the problem still exists.
Быстрое обучение и получение диплома магистра – возможно ли это?
My brother recommended I might like this blog. He was once entirely right. This publish actually made my day. You can not imagine simply how a lot time I had spent for this info! Thanks!
hello there and thank you for your information ? I?ve certainly picked up anything new from right here. I did alternatively experience some technical points the usage of this website, as I skilled to reload the site lots of occasions previous to I could get it to load correctly. I have been considering in case your web hosting is OK? Now not that I’m complaining, but sluggish loading cases occasions will sometimes affect your placement in google and can injury your quality rating if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Anyway I am including this RSS to my email and can look out for a lot extra of your respective interesting content. Make sure you update this again soon..
Тут можно преобрести сейф для пистолета и ружья купить оружейный сейф в москве
What i don’t realize is actually how you’re not actually much more well-liked than you might be now. You are very intelligent. You realize thus significantly relating to this subject, made me personally consider it from so many varied angles. Its like men and women aren’t fascinated unless it is one thing to accomplish with Lady gaga! Your own stuffs nice. Always maintain it up!
Процесс получения диплома стоматолога: реально ли это сделать быстро?
almazremont.ru/diplom-o-visshem-obrazovanii-kupit-v-kazani.html