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

15,754 Responses

  1. Hi! This is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us beneficial information to work on. You have done a marvellous job!

  2. A precondition for such credit is that banks have to be confident that the saved product shall be obtainable if they should name on the collateral; this implies the existence of a dependable community of certified warehouses.

  3. Hi, Neat post. There’s a problem with your website in internet explorer, would test this? IE still is the market leader and a huge portion of people will miss your magnificent writing because of this problem.

  4. Thanks for revealing your ideas listed here. The other factor is that whenever a problem develops with a laptop motherboard, folks should not consider the risk of repairing that themselves for if it is not done right it can lead to permanent damage to the whole laptop. It will always be safe to approach the dealer of the laptop for that repair of motherboard. They will have technicians that have an expertise in dealing with laptop motherboard complications and can make right analysis and accomplish repairs.

  5. This page was last edited on 31 July 2024, at 05:02 (UTC).

  6. February 18, 1945 French Algeria Algiers Briefed U.S.

  7. grand blue表示:

    I do trust all of the concepts you have introduced on your post. They are very convincing and will certainly work. Nonetheless, the posts are too short for beginners. May just you please prolong them a bit from next time? Thanks for the post.

  8. I appreciate, cause I found just what I was looking for. You have ended my four day long hunt! God Bless you man. Have a nice day. Bye

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

  10. Thanks for your article. I also feel that laptop computers have gotten more and more popular nowadays, and now tend to be the only type of computer used in a household. This is because at the same time actually becoming more and more inexpensive, their computing power keeps growing to the point where they’re as powerful as desktop coming from just a few years ago.

  11. It?s hard to search out knowledgeable people on this subject, however you sound like you recognize what you?re talking about! Thanks

  12. I do agree with all the ideas you’ve presented in your post. They’re very convincing and will definitely work. Still, the posts are very short for beginners. Could you please extend them a bit from next time? Thanks for the post.

  13. The board units policies for the municipality given below the Pennsylvania Second Class Township Code.

  14. I’m extremely inspired with your writing abilities and also with the structure to your blog. Is that this a paid topic or did you customize it your self? Anyway keep up the excellent quality writing, it is uncommon to see a great weblog like this one today..

  15. Center for Digital Government.

  16. One thing I want to say is always that car insurance cancelling is a terrifying experience so if you’re doing the right things like a driver you’ll not get one. A number of people do are sent the notice that they have been officially dumped by their insurance company and several have to fight to get supplemental insurance after having a cancellation. Cheap auto insurance rates are generally hard to get from cancellation. Knowing the main reasons for auto insurance cancelling can help owners prevent getting rid of in one of the most important privileges available. Thanks for the concepts shared by your blog.

  17. A powerful share, I simply given this onto a colleague who was doing just a little evaluation on this. And he in reality bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If attainable, as you grow to be experience, would you thoughts updating your blog with more particulars? It’s extremely helpful for me. Massive thumb up for this weblog publish!

  18. Air suspension is a automobile modification that is often utilized by auto lovers.

  19. Jones, Peter; Consolation, Daphne; Hillier, David (2005).

  20. Most of an application is run instantly as PowerPC code (which would not be doable on Intel-based mostly Macs).

  21. Sinopec reported 2019 revenues of ¥2.966 trillion.

  22. Whatever “romantic” fashion means to you, you possibly can create it even within the smallest space.

  23. Annual Report 2018 (PDF) (Report).

  24. The Fed’s two-half technique was thoroughly profitable, since lending to securities companies by giant banks in Chicago and particularly in New York elevated substantially, usually nearly doubling.

  25. Plankinton & Armour Firm.

  26. Can I simply say what a reduction to find somebody who really knows what theyre speaking about on the internet. You definitely know methods to convey a difficulty to mild and make it important. More people have to learn this and understand this side of the story. I cant believe youre not more in style because you definitely have the gift.

  27. Hello 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 require any coding expertise to make your own blog? Any help would be greatly appreciated!

  28. Hello there! 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 website addresses a lot of the same subjects as yours and I think we could greatly benefit from each other. If you happen to be interested feel free to send me an email. I look forward to hearing from you! Great blog by the way!

  29. zetman pdf表示:

    I like the helpful info you provide in your articles. I?ll bookmark your blog and check again here frequently. I am quite sure I will learn a lot of new stuff right here! Good luck for the next!

  30. I?m not sure where you’re getting your info, but great topic. I needs to spend some time learning more or understanding more. Thanks for great information I was looking for this info for my mission.

發佈留言

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