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
    }
}

You may also like...

11,365 Responses

  1. Thanks for your writing. I would also love to say that the health insurance dealer also works well with the benefit of the coordinators of your group insurance coverage. The health agent is given a summary of benefits wanted by someone or a group coordinator. What a broker really does is look for individuals and also coordinators which usually best go with those needs. Then he reveals his recommendations and if each party agree, the particular broker formulates a binding agreement between the two parties.

  2. I enjoy what you guys are usually up too. This sort of clever work and reporting! Keep up the fantastic works guys I’ve you guys to my personal blogroll.

  3. Turkey Tours表示:

    Hello there! This post could not be written any better! Reading through this post reminds me of my old room mate! He always kept talking about this. I will forward this post to him. Pretty sure he will have a good read. Thanks for sharing!

  4. Italy Tours表示:

    This really answered my downside, thank you!

  5. TomasRop表示:

    farmacia online senza ricetta: Farmacie on line spedizione gratuita – migliori farmacie online 2024

  6. I do trust all the ideas you’ve introduced to your post. They are really convincing and can certainly work. Still, the posts are too short for newbies. May just you please extend them a bit from subsequent time? Thank you for the post.

  7. Online Poker表示:

    Here is my web-site :: Online Poker

  8. I have realized that in unwanted cameras, exceptional sensors help to {focus|concentrate|maintain focus|target|a**** automatically. The actual sensors regarding some cams change in contrast, while others start using a beam associated with infra-red (IR) light, particularly in low light. Higher spec cameras often use a mix of both models and probably have Face Priority AF where the camera can ‘See’ a new face and focus only in that. Thank you for sharing your ideas on this site.

  9. Simply wish to say your article is as astonishing. The clearness in your post is just cool and i could assume you are an expert on this subject. Well with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please keep up the rewarding work.

  10. Hmm is anyone else encountering problems with the pictures on this blog loading? I’m trying to find out if its a problem on my end or if it’s the blog. Any feedback would be greatly appreciated.

  11. I’m so happy to read this. This is the type of manual that needs to be given and not the accidental misinformation that is at the other blogs. Appreciate your sharing this best doc.

  12. As I web site possessor I believe the content matter here is rattling great , appreciate it for your hard work. You should keep it up forever! Good Luck.

  13. TomasRop表示:

    farmacie online affidabili: Farmacia online piu conveniente – top farmacia online

  14. Hello there! This is my first comment here so I just wanted to give a quick shout out and say I truly enjoy reading your articles. Can you suggest any other blogs/websites/forums that go over the same topics? Thanks!

  15. RandyLunda表示:

    viagra naturale in farmacia senza ricetta: viagra farmacia – viagra generico recensioni

  16. RandyLunda表示:

    Farmacie on line spedizione gratuita: farmacia online migliore – Farmacia online piГ№ conveniente

  17. RandyLunda表示:

    top farmacia online: Farmacie on line spedizione gratuita – Farmacia online miglior prezzo

  18. This article is a breath of fresh air! The author’s unique perspective and insightful analysis have made this a truly fascinating read. I’m thankful for the effort she has put into producing such an educational and mind-stimulating piece. Thank you, author, for offering your knowledge and sparking meaningful discussions through your exceptional writing!

  19. Italy Tours表示:

    Thanks for sharing your ideas right here. The other point is that any time a problem occurs with a pc motherboard, people should not consider the risk of repairing this themselves because if it is not done right it can lead to permanent damage to an entire laptop. It’s usually safe to approach your dealer of a laptop with the repair of that motherboard. They’ve technicians who definitely have an experience in dealing with pc motherboard difficulties and can have the right diagnosis and perform repairs.

  20. Does your site have a contact page? I’m having a tough time locating it but, I’d like to send you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing. Either way, great website and I look forward to seeing it develop over time.

  21. I’ve learned quite a few important things as a result of your post. I might also like to say that there might be situation where you will get a loan and do not need a co-signer such as a Government Student Support Loan. However, if you are getting a loan through a common bank or investment company then you need to be made ready to have a cosigner ready to make it easier for you. The lenders can base their own decision on the few aspects but the most important will be your credit history. There are some loan providers that will likewise look at your work history and decide based on this but in almost all cases it will depend on your credit score.

  22. Via my investigation, shopping for consumer electronics online may be easily expensive, although there are some how-to’s that you can use to acquire the best deals. There are often ways to locate discount promotions that could help to make one to come across the best technology products at the cheapest prices. Thanks for your blog post.

  23. TomasRop表示:

    п»їFarmacia online migliore: kamagra gel – farmacia online

  24. Normally I don’t learn article on blogs, however I would like to say that this write-up very forced me to try and do so! Your writing taste has been amazed me. Thanks, very nice article.

  25. Thanks for your recommendations on this blog. One thing I wish to say is that often purchasing gadgets items over the Internet is certainly not new. In fact, in the past several years alone, the marketplace for online electronic devices has grown drastically. Today, you will find practically any kind of electronic gizmo and other gadgets on the Internet, which include cameras as well as camcorders to computer elements and gaming consoles.

  26. Thanks for your posting on this site. From my personal experience, there are times when softening up a photograph may possibly provide the digital photographer with an amount of an artistic flare. Sometimes however, this soft blur isn’t exactly what you had at heart and can usually spoil an otherwise good photo, especially if you intend on enlarging that.

  27. Timothyzew表示:

    http://farmait.store/# farmacia online

  28. I was very happy to find this internet-site.I wished to thanks on your time for this excellent read!! I definitely having fun with every little bit of it and I have you bookmarked to take a look at new stuff you blog post.

  29. Timothyzew表示:

    https://avanafil.pro/# comprare farmaci online con ricetta

  30. Fantastic beat ! I would like to apprentice whilst you amend your site, how can i subscribe for a blog site? The account helped me a applicable deal. I have been a little bit acquainted of this your broadcast offered bright clear idea

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。