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

10,427 Responses

  1. We are a bunch of volunteers and starting a new scheme in our community. Your site offered us with useful info to work on. You have performed an impressive task and our entire group might be thankful to you.

  2. I haven?t checked in here for some time since I thought it was getting boring, but the last few posts are good quality so I guess I will add you back to my daily bloglist. You deserve it my friend 🙂

  3. Excellent items from you, man. I’ve take note your stuff prior to and you’re just too fantastic. I actually like what you have received here, really like what you’re saying and the way by which you say it. You are making it enjoyable and you still take care of to keep it wise. I cant wait to learn much more from you. This is really a terrific site.

  4. I love your wp theme, exactly where do you down load it through?

  5. cbd massage表示:

    Oh my goodness! an incredible article dude. Thank you Nevertheless I’m experiencing subject with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting identical rss drawback? Anybody who knows kindly respond. Thnkx

  6. Hello there, I found your blog by the use of Google while looking for a similar topic, your website came up, it appears great. I’ve bookmarked it in my google bookmarks.

  7. Great site! I recommend to everyone!kms pico

  8. Hiya, I’m really glad I have found this info. Today bloggers publish only about gossips and net and this is actually frustrating. A good website with interesting content, this is what I need. Thank you for keeping this site, I will be visiting it. Do you do newsletters? Cant find it.

  9. Another thing I have noticed is for many people, bad credit is the results of circumstances outside of their control. One example is they may be really saddled with illness so they really have more bills for collections. It could be due to a employment loss or the inability to do the job. Sometimes divorce can send the financial circumstances in an opposite direction. Thanks sharing your thinking on this blog.

  10. cbd massage表示:

    Oh my goodness! an incredible article dude. Thank you Nevertheless I’m experiencing challenge with ur rss . Don?t know why Unable to subscribe to it. Is there anybody getting similar rss drawback? Anybody who knows kindly respond. Thnkx

  11. Thanks for these pointers. One thing I should also believe is always that credit cards giving a 0 rate of interest often entice consumers together with zero interest, instant endorsement and easy internet balance transfers, nonetheless beware of the number one factor that will certainly void your 0 easy street annual percentage rate plus throw one out into the bad house in no time.

  12. Kazanmak icin harika bir kumarhane Sweet bonanza

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

  14. bokep jilbab表示:

    Wonderful paintings! That is the kind of info that are supposed to be shared around the internet. Shame on Google for no longer positioning this put up upper! Come on over and seek advice from my web site . Thanks =)

  15. Sizin icin en iyi online casino Sweet bonanza

  16. One thing I’d really like to comment on is that weightloss routine fast is possible by the correct diet and exercise. A person’s size not simply affects the look, but also the complete quality of life. Self-esteem, despression symptoms, health risks, in addition to physical ability are damaged in extra weight. It is possible to just make everything right and still gain. If this happens, a condition may be the reason. While a lot of food rather than enough workout are usually the culprit, common medical ailments and widespread prescriptions can certainly greatly increase size. Thanks a bunch for your post right here.

  17. Based on my observation, after a foreclosures home is available at a sale, it is common for your borrower to be able to still have some sort ofthat remaining unpaid debt on the mortgage. There are many loan companies who try to have all service fees and liens paid off by the future buyer. Having said that, depending on specific programs, laws, and state legal guidelines there may be a few loans that are not easily solved through the switch of financial loans. Therefore, the responsibility still falls on the borrower that has received his or her property in foreclosure process. Thank you for sharing your ideas on this blog site.

  18. I was more than happy to seek out this internet-site.I wished to thanks to your time for this glorious read!! I definitely having fun with each little little bit of it and I’ve you bookmarked to check out new stuff you blog post.

  19. Great site! I recommend to everyone!kmspico download

  20. Hello my friend! I want to say that this article is amazing, nice written and include almost all significant infos. I would like to see more posts like this.

  21. I am not sure where you are getting your info, but good topic. I needs to spend some time learning more or understanding more. Thanks for wonderful information I was looking for this information for my mission.

  22. cbd massage表示:

    I just could not depart your site prior to suggesting that I really enjoyed the standard information a person provide for your visitors? Is going to be back often in order to check up on new posts

  23. Ivhavo表示:

    buy generic cyclobenzaprine – vasotec for sale cost vasotec 5mg

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

  25. Thank you a bunch for sharing this with all folks you really know what you’re talking approximately! Bookmarked. Kindly also discuss with my site =). We can have a hyperlink trade arrangement among us!

  26. Hello there, I discovered your blog by means of Google even as looking for a similar matter, your site got here up, it appears good. I’ve bookmarked it in my google bookmarks.

  27. What?s Going down i’m new to this, I stumbled upon this I have found It absolutely useful and it has aided me out loads. I hope to contribute & aid other customers like its aided me. Great job.

  28. Adrianjug表示:

    KMSpico Download | Official KMS Website New July 2024
    ez активатор
    Are you looking for the best tool to activate your Windows & Office? Then you should download and install KMSpico, as it is one of the best tools everyone should have. In this article, I will tell you everything about this fantastic tool, even though I will also tell you if this is safe to use.

    In this case, don’t forget to read this article until the end, so you don’t miss any critical information. This guide is for both beginners and experts as I came up with some of the rumours spreading throughout the internet.

    Perhaps before we move towards downloading or installing a section, we must first understand this tool. You should check out the guide below on this tool and how it works; if you already know about it, you can move to another section.
    What is KMSPico?
    KMPico is a tool that is used to activate or get a license for Microsft Windows as well as for MS Office. It was developed by one of the most famous developers named, Team Daz. However, it is entirely free to use. There is no need to purchase it or spend money downloading it. This works on the principle of Microsft’s feature named Key Management Server, a.k.a KMS (KMSPico named derived from it).

    The feature is used for vast companies with many machines in their place. In this way, it is hard to buy a Windows License for each device,, which is why KMS introduced. Now a company has to buy a KMS server for them and use it when they can get a license for all their machines.

    However, this tool also works on it, and similarly, it creates a server on your machine and makes it look like a part of that server. One thing different is that this tool only keeps the product activated for 180 days. This is why it keeps running on your machine, renews the license keys after 180 days, and makes it a permanent activation.

    KMSAuto Net
    Microsoft Toolkit
    Windows Loader
    Windows 10 Activator
    Features
    We already know what this tool means, so let’s talk about some of the features you are getting along with KMSPico. Reading this will surely help you understand whether you are downloading the correct file.

    Ok, so here are some of the features that KMSPico provides:

    Activate Windows & Office

    We have already talked about this earlier, as using this tool, you will get the installation key for both Microsoft Products. Whether it is Windows or Office, you can get a license in no time; however, this supports various versions.

    Supports Multi-Arch

    Since this supports both products, it doesn’t mean you have to download separate versions for each arch. One version is enough, and you can get the license for both x32-bit or even the x64-bit.

    It Is Free To Use

    Undoubtedly, everything developed by Team Daz costs nothing to us. Similarly, using this tool won’t cost you either, as it is entirely free. Other than this, it doesn’t come with any ads, so using it won’t be any trouble.

    Permanent License

    Due to the KMS server, this tool installs on our PC, we will get the license key for the rest of our lives. This is because the license automatically renews after a few days. To keep it permanent, you must connect your machine to the internet once 180 days.

    Virus Free

    Now comes the main feature of this tool that makes it famous among others. KMSPico is 100% pure and clean from such viruses or trojans. The Virus Total scans it before uploading to ensure it doesn’t harm our visitors.

  29. Douglasslida表示:

    KMSpico: What is it?
    kmspico 9
    Operating systems and Office suites are among the primary Microsoft software items that still need to be paid for. Some consumers may find alternate activation methods due to the perceived expensive cost of these items. There may be restrictions, unforeseen interruptions, and persistent activation prompts if these items are installed without being properly activated.

    Our KMSpico app was created as a solution to this issue. By using this program, customers may access all of the functionality of Microsoft products and simplify the activation procedure.
    KMSPico is a universal activator designed to optimize the process of generating and registering license codes for Windows and Office. Functionally, it is similar to key generators, but with the additional possibility of automatic integration of codes directly into the system. It is worth paying attention to the versatility of the tool, which distinguishes it from similar activators.
    The above discussion primarily focused on the core KMS activator, the Pico app. Understanding what the program is, we can briefly mention KMSAuto, a tool with a simpler interface.

    By using the KMSPico tool, you can setup Windows&Office for lifetime activation. This is an essential tool for anybody looking to reveal improved features and go beyond limitations. Although it is possible to buy a Windows or Office key.

    KMSPico 11 (last update 2024) allows you to activate Windows 11/10/8 (8.1)/7 and Office 2021/2019/2016/2013/2010 for FREE.

  30. Great post. I was checking continuously this blog and I’m impressed! Very useful info specifically the last part 🙂 I care for such info a lot. I was looking for this certain information for a long time. Thank you and good luck.

發佈留言

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