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,450 Responses

  1. DominicJaw表示:

    reputable mexican pharmacies online: mexico drug stores pharmacies – purple pharmacy mexico price list

  2. fantastic post, very informative. I wonder why the other specialists of this sector do not notice this. You must continue your writing. I’m confident, you have a great readers’ base already!

  3. Nelsonbluck表示:

    medicine in mexico pharmacies: buying from online mexican pharmacy – mexican mail order pharmacies

  4. I have recently started a web site, the info you provide on this website has helped me tremendously. Thanks for all of your time & work.

  5. I discovered your blog website on google and examine just a few of your early posts. Continue to keep up the excellent operate. I simply extra up your RSS feed to my MSN News Reader. Seeking ahead to studying more from you later on!?

  6. Arnoldten表示:

    buying prescription drugs in mexico п»їbest mexican online pharmacies pharmacies in mexico that ship to usa

  7. Thanks for revealing your ideas listed here. The other factor is that every time a problem takes place with a computer motherboard, people should not consider the risk regarding repairing it themselves for if it is not done properly it can lead to irreparable damage to the complete laptop. It will always be safe just to approach a dealer of a laptop with the repair of that motherboard. They have got technicians who may have an know-how in dealing with laptop motherboard troubles and can carry out the right diagnosis and carry out repairs.

  8. I have realized that car insurance corporations know the automobiles which are prone to accidents as well as other risks. Additionally they know what type of cars are given to higher risk plus the higher risk they’ve the higher your premium amount. Understanding the simple basics of car insurance will help you choose the right sort of insurance policy that should take care of your requirements in case you become involved in any accident. Thank you sharing a ideas for your blog.

  9. Your web site doesn’t render appropriately on my iphone4 – you might wanna try and repair that

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

  11. Diplomi_vmEa表示:

    Добрый день!
    Купить документ ВУЗа вы можете в нашей компании.
    asxdiplomik.com/kupit-diplom-perm

  12. RichardWrifs表示:

    https://mexicandeliverypharma.online/# mexico drug stores pharmacies

  13. Hello! This is my 1st comment here so I just wanted to give a quick shout out and say I really enjoy reading through your blog posts. Can you recommend any other blogs/websites/forums that deal with the same subjects? Thank you so much!

  14. Heya i?m for the primary time here. I came across this board and I to find It really useful & it helped me out a lot. I am hoping to present one thing back and aid others like you aided me.

  15. I just couldn’t 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

  16. WayneCoirl表示:

    medication from mexico pharmacy: buying prescription drugs in mexico – buying from online mexican pharmacy

  17. DominicJaw表示:

    purple pharmacy mexico price list: purple pharmacy mexico price list – best online pharmacies in mexico

  18. Howdy! This is kind of off topic but I need some advice from an established blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about creating my own but I’m not sure where to begin. Do you have any ideas or suggestions? Appreciate it

  19. yourskin33表示:

    Wow that was strange. I just wrote an incredibly long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say superb blog!

  20. Magnificent website. A lot of useful information here. I am sending it to some friends ans also sharing in delicious. And obviously, thanks for your effort!

  21. Nelsonbluck表示:

    п»їbest mexican online pharmacies: mexican online pharmacies prescription drugs – mexican online pharmacies prescription drugs

  22. Thanks for enabling me to get new concepts about computer systems. I also have belief that certain of the best ways to help keep your notebook in leading condition is by using a hard plastic-type case, or maybe shell, which fits over the top of the computer. A majority of these protective gear are usually model precise since they are made to fit perfectly in the natural casing. You can buy these directly from the owner, or from third party places if they are designed for your notebook computer, however don’t assume all laptop could have a spend on the market. Just as before, thanks for your guidelines.

  23. Hmm it appears like your blog ate my first comment (it was super long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to everything. Do you have any tips for rookie blog writers? I’d really appreciate it.

  24. Hey! I know this is kind of off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one? Thanks a lot!

  25. Hi there 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 html coding knowledge to make your own blog? Any help would be greatly appreciated!

  26. Arnoldten表示:

    mexico drug stores pharmacies mexico drug stores pharmacies best online pharmacies in mexico

  27. My partner and I stumbled over here coming from a different page and thought I should check things out. I like what I see so now i’m following you. Look forward to looking at your web page for a second time.

  28. Thanks for revealing your ideas listed here. The other issue is that any time a problem comes up with a computer system motherboard, individuals should not take the risk connected with repairing the item themselves for if it is not done right it can lead to irreparable damage to the full laptop. In most cases, it is safe to approach a dealer of any laptop with the repair of its motherboard. They will have technicians with an skills in dealing with pc motherboard troubles and can have the right prognosis and carry out repairs.

  29. Hey! I just wanted to ask if you ever have any trouble with hackers? My last blog (wordpress) was hacked and I ended up losing several weeks of hard work due to no backup. Do you have any solutions to protect against hackers?

發佈留言

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