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

  1. I have been exploring for a little for any high quality articles or blog posts on this kind of space . Exploring in Yahoo I ultimately stumbled upon this site. Reading this information So i am glad to convey that I’ve an incredibly excellent uncanny feeling I found out just what I needed. I most definitely will make certain to don?t forget this site and give it a glance regularly.

  2. whoah this blog is excellent i love reading your articles. Keep up the great work! You know, lots of people are searching around for this information, you can help them greatly.

  3. Hello my loved one! I want to say that this article is awesome, great written and come with almost all significant infos. I?d like to see more posts like this .

  4. Hello there, You have done an incredible job. I will definitely digg it and personally suggest to my friends. I’m sure they’ll be benefited from this site.

  5. Thanks for your writing. I would also love to say a health insurance dealer also works best for the benefit of the particular coordinators of a group insurance policy. The health broker is given a listing of benefits desired by an individual or a group coordinator. What any broker will is look for individuals or coordinators which often best match those demands. Then he offers his suggestions and if each party agree, this broker formulates legal contract between the two parties.

  6. Hello there, I found your site via Google while looking for a related topic, your site came up, it looks good. I’ve bookmarked it in my google bookmarks.

  7. I have realized that over the course of making a relationship with real estate homeowners, you’ll be able to get them to understand that, in every real estate purchase, a commission amount is paid. Eventually, FSBO sellers don’t “save” the fee. Rather, they struggle to earn the commission by doing the agent’s work. In the process, they expend their money and also time to accomplish, as best they can, the duties of an agent. Those assignments include displaying the home by marketing, delivering the home to buyers, building a sense of buyer desperation in order to trigger an offer, arranging home inspections, controlling qualification checks with the financial institution, supervising maintenance tasks, and assisting the closing.

  8. Danielned表示:

    Я в глубоком недоумении от того, как наша справедливость может быть настолько искажена! Кооператив “Бест Вей” стал для меня и моей семьи настоящим спасением от банковских кредитов и ипотечных долгов. Но теперь, когда мы наконец-то близки к мечте о собственном жилье, наше будущее висит на волоске. Вместо того чтобы защищать честных пайщиков, власти блокируют счета и конфисковывают активы кооператива под предлогом мошенничества. Где справедливость? Где законность? Мы, обычные люди, страдаем от политически мотивированных игр, которые уничтожают те возможности, за которые мы так трудились. Я требую, чтобы дело было рассмотрено честно и открыто, чтобы восстановить не только наши права, но и веру в нашу правовую систему.

  9. Hey, you used to write excellent, but the last several posts have been kinda boring? I miss your tremendous writings. Past several posts are just a bit out of track! come on!

  10. Thank you for any other informative website. Where else could I get that kind of information written in such an ideal method? I’ve a venture that I am just now running on, and I have been at the look out for such info.

  11. Good blog! I really love how it is easy on my eyes and the data are well written. I’m wondering how I could be notified whenever a new post has been made. I have subscribed to your feed which must do the trick! Have a nice day!

  12. One thing I would really like to reply to is that weightloss routine fast is possible by the appropriate diet and exercise. An individual’s size not simply affects the look, but also the overall quality of life. Self-esteem, depressive disorders, health risks, plus physical ability are disturbed in excess weight. It is possible to make everything right and at the same time having a gain. In such a circumstance, a medical problem may be the root cause. While an excessive amount of food but not enough body exercise are usually to blame, common medical ailments and key prescriptions may greatly increase size. Many thanks for your post here.

  13. I am really loving the theme/design of your blog. Do you ever run into any internet browser compatibility problems? A couple of my blog visitors have complained about my blog not operating correctly in Explorer but looks great in Firefox. Do you have any recommendations to help fix this problem?

  14. I’m typically to blogging and i actually admire your content. The article has actually peaks my interest. I am going to bookmark your site and keep checking for brand spanking new information.

  15. Promokod_hwml表示:

    Экономьте с нашими проверенными промокодами. Экономьте с нашими проверенными промокодами. .

  16. Promokod_nrml表示:

    Полезные советы по использованию промокодов. https://free-promocode.ru .

  17. Thanks for your post. I would also like to say that the very first thing you will need to do is to see if you really need credit restoration. To do that you simply must get your hands on a copy of your credit file. That should really not be difficult, since government makes it necessary that you are allowed to have one free of charge copy of your real credit report every year. You just have to consult the right men and women. You can either find out from the website owned by the Federal Trade Commission or contact one of the major credit agencies straight.

  18. I think other web-site proprietors should take this web site as an model, very clean and fantastic user genial style and design, let alone the content. You are an expert in this topic!

  19. hey there and thank you for your information ? I?ve certainly picked up something new from right here. I did however expertise a few technical points using this web site, since I experienced to reload the site many times previous to I could get it to load properly. I had been wondering if your web host is OK? Not that I am complaining, but slow loading instances times will often affect your placement in google and can damage your quality score if advertising and marketing with Adwords. Well I am adding this RSS to my e-mail and could look out for a lot more of your respective fascinating content. Make sure you update this again soon..

  20. Dnrtszg表示:

    Привет!
    Заказать документ университета вы сможете в нашем сервисе.
    ast-diplomas.com/kupit-diplom-magistra
    Успехов в учебе!

  21. Fantastic goods from you, man. I’ve understand your stuff previous to and you are just too wonderful. I really like what you have acquired here, certainly like what you’re saying and the way in which you say it. You make it enjoyable and you still take care of to keep it smart. I can’t wait to read much more from you. This is really a terrific web site.

  22. I?ve been exploring for a little bit for any high-quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this site. Reading this info So i?m happy to convey that I have an incredibly good uncanny feeling I discovered just what I needed. I most certainly will make sure to don?t forget this site and give it a look on a constant basis.

  23. Audio started playing as soon as I opened this internet site, so irritating!

  24. hi!,I really like your writing so so much! proportion we be in contact more about your article on AOL? I require a specialist on this area to resolve my problem. Maybe that is you! Looking ahead to see you.

  25. Greetings! This is my first visit to your blog! We are a collection of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done a extraordinary job!

  26. Thanks for your posting. What I want to say is that when evaluating a good on the internet electronics shop, look for a site with total information on critical indicators such as the personal privacy statement, basic safety details, any payment procedures, and various terms and also policies. Constantly take time to read the help in addition to FAQ pieces to get a greater idea of the way the shop functions, what they are able to do for you, and ways in which you can make best use of the features.

  27. Hi there, just became alert to your blog through Google, and found that it’s truly informative. I?m going to watch out for brussels. I will be grateful if you continue this in future. Many people will be benefited from your writing. Cheers!

  28. I don?t even know how I ended up here, but I thought this post was great. I don’t know who you are but certainly you’re going to a famous blogger if you are not already 😉 Cheers!

發佈留言

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