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 } }
One important thing is that if you are searching for a education loan you may find that you will need a co-signer. There are many situations where this is correct because you might find that you do not use a past credit rating so the mortgage lender will require that you’ve someone cosign the money for you. Interesting post.
I enjoy what you guys tend to be up too. This kind of clever work and reporting! Keep up the awesome works guys I’ve included you guys to blogroll.
Orgulhamo-nos de servir clientes de diversas origens etnicas e consideramos a nossa missao a promocao da sua integracao na vanguarda dos negocios europeus. Adaptar-se rapidamente as flutuacoes da industria e enfrentar varios desafios sao essenciais para a nossa abordagem. Alem disso, defendemos uma etica profissional rigorosa, acreditando que sao essenciais para uma cooperacao frutifera. Nossos servicos sao adaptados para atender as necessidades especificas de clientes internacionais e podem ser ainda mais personalizados mediante solicitacao individual.
Dinamica
Num cenario global em constante evolucao, a Regulated United Europe permanece agil e reativa. Priorizamos a eficiencia para honrar o tempo de nossos clientes, prestando prontamente servicos corporativos, contabeis e juridicos. Em meio a volatilidade, a agilidade de uma empresa define seu sucesso, e estamos comprometidos em fornecer um servico de qualidade no menor prazo possivel. Assim, nos esforcamos para responder a todas as duvidas dos clientes em poucas horas.
I have witnessed that intelligent real estate agents everywhere you go are Promotion. They are seeing that it’s in addition to placing a sign post in the front yard. It’s really with regards to building associations with these dealers who one of these days will become purchasers. So, once you give your time and energy to aiding these sellers go it alone : the “Law regarding Reciprocity” kicks in. Interesting blog post.
Hello, you used to write great, but the last several posts have been kinda boring? I miss your great writings. Past few posts are just a little out of track! come on!
I really believe that a property foreclosures can have a major effect on the borrower’s life. Foreclosures can have a 7 to decade negative relation to a client’s credit report. The borrower that has applied for a home loan or any kind of loans for instance, knows that the actual worse credit rating is usually, the more complicated it is to get a decent bank loan. In addition, it might affect the borrower’s chance to find a respectable place to let or rent, if that will become the alternative property solution. Thanks for your blog post.
Thanks for your article on this blog. From my personal experience, many times softening way up a photograph may provide the digital photographer with an amount of an imaginative flare. Many times however, this soft cloud isn’t precisely what you had at heart and can in many cases spoil a normally good image, especially if you intend on enlarging them.
Great post. I was checking continuously this blog and I’m impressed! Extremely helpful info specially the last part 🙂 I care for such information much. I was seeking this particular information for a very long time. Thank you and good luck.
Very nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed surfing around your blog posts. In any case I will be subscribing to your rss feed and I hope you write again very soon!
Generally I do not read article on blogs, however I wish to say that this write-up very pressured me to take a look at and do so! Your writing taste has been surprised me. Thank you, quite nice article.
hello!,I love your writing very so much! proportion we communicate more about your article on AOL? I need an expert in this house to resolve my problem. May be that’s you! Looking ahead to look you.
Woah! I’m really digging the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between usability and appearance. I must say that you’ve done a great job with this. Additionally, the blog loads extremely fast for me on Chrome. Superb Blog!
Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a little bit, but instead of that, this is wonderful blog. An excellent read. I’ll definitely be back.
Thanks a lot for your post. I want to write my opinion that the expense of car insurance varies widely from one plan to another, for the reason that there are so many different issues which play a role in the overall cost. For example, the model and make of the car or truck will have a massive bearing on the charge. A reliable old family auto will have a lower priced premium than just a flashy expensive car.
You actually make it seem so easy with your presentation but I find this matter to be really something which I think I would never understand. It seems too complex and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it!
Thanks for the auspicious writeup. It in truth used to be a entertainment account it. Look advanced to more brought agreeable from you! However, how could we be in contact?
Всё о покупке аттестата о среднем образовании: полезные советы
I have seen loads of useful factors on your website about desktops. However, I have the judgment that netbooks are still more or less not powerful adequately to be a good choice if you generally do tasks that require lots of power, such as video croping and editing. But for net surfing, microsoft word processing, and a lot other common computer work they are just great, provided you may not mind the screen size. Thank you for sharing your thinking.
I am usually to blogging and i actually appreciate your content. The article has really peaks my interest. I am going to bookmark your web site and hold checking for new information.
An added important component is that if you are a mature person, travel insurance intended for pensioners is something that is important to really take into consideration. The more mature you are, the harder at risk you might be for making something bad happen to you while in most foreign countries. If you are not really covered by some comprehensive insurance, you could have a few serious problems. Thanks for revealing your good tips on this web blog.
Appreciate you for sharing all these wonderful articles. In addition, the ideal travel and medical insurance strategy can often eradicate those problems that come with traveling abroad. Some sort of medical emergency can soon become very expensive and that’s certain to quickly decide to put a financial weight on the family finances. Setting up in place the best travel insurance bundle prior to leaving is worth the time and effort. Thank you
Greetings! I know this is kinda off topic however I’d figured I’d ask. Would you be interested in trading links or maybe guest writing a blog article or vice-versa? My blog discusses a lot of the same subjects as yours and I think we could greatly benefit from each other. If you are interested feel free to send me an e-mail. I look forward to hearing from you! Awesome blog by the way!
mexican online pharmacies prescription drugs: mexico drug stores pharmacies – medication from mexico pharmacy
https://easyrxcanada.com/# legitimate canadian mail order pharmacy
I would also like to state that most individuals that find themselves with out health insurance can be students, self-employed and people who are unemployed. More than half of those uninsured are under the age of Thirty-five. They do not experience they are wanting health insurance because they’re young plus healthy. Their particular income is generally spent on housing, food, plus entertainment. Many people that do represent the working class either whole or as a hobby are not offered insurance by means of their jobs so they go without as a result of rising expense of health insurance in the United States. Thanks for the concepts you write about through this site.
I?d should check with you here. Which is not one thing I usually do! I take pleasure in studying a submit that will make folks think. Additionally, thanks for allowing me to comment!
best online pharmacies in mexico: mexican mail order pharmacies – mexico drug stores pharmacies
Thanks for the good writeup. It in truth used to be a entertainment account it. Glance advanced to more added agreeable from you! However, how could we be in contact?
I am so happy to read this. This is the kind of manual that needs to be given and not the random misinformation that is at the other blogs. Appreciate your sharing this best doc.
Do you have a spam problem on this site; I also am a blogger, and I was wanting to know your situation; we have created some nice procedures and we are looking to trade strategies with other folks, why not shoot me an e-mail if interested.