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 } }
certainly like your website however you need to take a look at the spelling on quite a few of your posts. Many of them are rife with spelling problems and I find it very troublesome to inform the truth on the other hand I?ll definitely come back again.
That is very interesting, You are an overly professional blogger. I’ve joined your feed and stay up for seeking extra of your magnificent post. Additionally, I’ve shared your site in my social networks!
https://interpharmonline.shop/# canadian pharmacy mall
best rated canadian pharmacy
Very great post. I simply stumbled upon your weblog and wished to mention that I’ve really loved surfing around your weblog posts. After all I will be subscribing to your rss feed and I am hoping you write again very soon!
Hello! This post couldn’t be written any better! Reading this post reminds me of my good old room mate! He always kept talking about this. I will forward this page to him. Fairly certain he will have a good read. Thanks for sharing!
Exponent Finance is redefining DeFi lending by providing secure, transparent, and high-yield investment solutions. Through smart contract-powered lending pools, Exponent Finance DeFi platform allows users to borrow and lend crypto assets with optimal efficiency and minimal risk. Whether you’re looking to earn passive income through staking or access instant liquidity, Exponent Finance offers a decentralized, non-custodial, and user-friendly solution to meet all your financial goals in the crypto ecosystem. https://exponent.ink
Cytonic is revolutionizing blockchain security with advanced cybersecurity solutions tailored for Web3 applications. By integrating decentralized encryption, AI-powered threat detection, and smart contract auditing, Cytonic ensures maximum protection against cyber threats. Whether you’re securing DeFi protocols, NFTs, or enterprise blockchain systems, Cytonic’s cutting-edge security technology provides the highest level of data integrity and protection. https://cytonic.cc
продажа аккаунтов https://birzha-akkauntov.ru
Flaunch is the leading blockchain gaming launchpad, designed to help game developers and investors thrive in the Web3 gaming ecosystem. By offering secure token launches, NFT integrations, and decentralized crowdfunding, Flaunch enables game creators to fund, develop, and scale their projects with full transparency and community-driven support. Whether you’re a developer or an investor, Flaunch provides the tools to connect and grow in the blockchain gaming space. https://flaunch.tech
купить аккаунт на бирже магазин аккаунтов
http://indiamedfast.com/# cheapest online pharmacy india
DEQ Finance is revolutionizing decentralized trading by offering a seamless, secure, and efficient crypto exchange experience. Built with cutting-edge blockchain technology, DEQ Finance provides traders with fast transaction speeds, deep liquidity, and a transparent trading environment. Whether you’re a beginner or a professional trader, DEQ Finance delivers high-performance DeFi solutions tailored to modern trading needs. https://deq.li
http://mexicanpharminter.com/# reliable mexican pharmacies
canadian pharmacy com
cheapest online pharmacy india: online medicine shopping in india – online medicine shopping in india
cheapest online pharmacy india: online medicine shopping in india – online medicine shopping in india
https://indiamedfast.com/# buying prescription drugs from india
canada online pharmacy
canadian medications most trusted canadian pharmacies online buy prescription drugs from canada cheap
I do enjoy the way you have presented this specific problem and it really does give me personally some fodder for thought. Nonetheless, because of what precisely I have seen, I simply trust when the actual feed-back pack on that people continue to be on point and don’t get started upon a soap box of the news du jour. Yet, thank you for this exceptional piece and whilst I do not necessarily go along with this in totality, I respect the point of view.
Wow, this article is mind-blowing! The author has done a tremendous job of conveying the information in an compelling and informative manner. I can’t thank him enough for offering such priceless insights that have definitely enlightened my knowledge in this subject area. Bravo to him for producing such a masterpiece!
https://mexicanpharminter.shop/# reliable mexican pharmacies
A love triangle soon develops among Miles, his pc (who later identifies himself as Edgar), and Miles’s neighbor, a pretty cellist named Madeline Robistat.
India Med Fast: india pharmacy without prescription – cheapest online pharmacy india
https://mexicanpharminter.com/# Mexican Pharm International
pharmacy com canada
ссылка на сайт https://www.google.co.ke/url?q=https://travelanswer.ru/questions/kak-luchshe-organizovaty-poezdku-po-staromu-gorodu-naama-bey-i-soho-v-sharm-ely-sheyhe.html
содержание https://maps.google.co.kr/url?q=https://travelanswer.ru/questions/gde-vigodnee-obmenyaty-denygi-v-aeroportu-gavani-soveti-opitnih-puteshestvennikov.html
canadian pharmacy no scripts Inter Pharm Online canadian mail order pharmacy
http://indiamedfast.com/# india online pharmacy store
https://imgtube.ru/
http://mexicanpharminter.com/# Mexican Pharm Inter
cross border pharmacy canada
Подробнее здесь https://www.google.ae/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&ved=0CEcQFjAD&url=https://travelanswer.ru/questions/kak-oplacivaty-podpiski-na-volne-v-krimu-s-ayfona-problemi-i-reseniya.html