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

20,899 Responses

  1. Just want to say your article is as surprising. The clearness in your post is simply cool and i could assume you’re 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 gratifying work.

  2. Along with every thing which seems to be developing inside this area, a significant percentage of perspectives are rather radical. However, I appologize, but I can not subscribe to your whole plan, all be it radical none the less. It would seem to everybody that your remarks are not completely rationalized and in fact you are yourself not wholly certain of your assertion. In any event I did take pleasure in examining it.

  3. Music began playing as soon as I opened this blog, so frustrating!

  4. Have you ever thought about including a little bit more than just your articles? I mean, what you say is fundamental and everything. However think about if you added some great graphics or video clips to give your posts more, “pop”! Your content is excellent but with pics and clips, this site could certainly be one of the greatest in its field. Wonderful blog!

  5. My brother recommended I would possibly like this website. He was entirely right. This put up truly made my day. You cann’t believe just how a lot time I had spent for this information! Thanks!

  6. Excellent goods from you, man. I have understand your stuff previous to and you are just too wonderful. I really like what you have acquired here, certainly like what you’re stating and the way in which you say it. You make it entertaining and you still care for to keep it smart. I can not wait to read far more from you. This is actually a terrific website.

  7. I would also like to say that most of those that find themselves without the need of health insurance are usually students, self-employed and those that are jobless. More than half with the uninsured are really under the age of Thirty five. They do not really feel they are wanting health insurance as they are young and also healthy. The income is usually spent on property, food, plus entertainment. Lots of people that do work either full or not professional are not provided insurance by means of their work so they go without owing to the rising tariff of health insurance in the states. Thanks for the ideas you discuss through this web site.

  8. Thanks for the tips you have provided here. Moreover, I believe there are several factors that really keep your car insurance policy premium down. One is, to consider buying vehicles that are within the good report on car insurance companies. Cars which are expensive are definitely more at risk of being lost. Aside from that insurance is also depending on the value of your vehicle, so the higher in price it is, then higher a premium you make payment for.

  9. Cool blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple tweeks would really make my blog stand out. Please let me know where you got your design. Cheers

  10. I do consider all of the ideas you have presented on your post. They are very convincing and will definitely work. Still, the posts are too short for novices. May just you please prolong them a little from next time? Thanks for the post.

  11. Darrelherse表示:

    guvenilir slot siteleri 2024: slot bahis siteleri – slot siteleri bonus veren

  12. Darrelherse表示:

    slot oyun siteleri: slot oyun siteleri – en cok kazandiran slot siteleri

  13. vk nim表示:

    excellent submit, very informative. I’m wondering why the opposite specialists of this sector do not notice this. You should proceed your writing. I am sure, you have a huge readers’ base already!

  14. bestzabzeed表示:

    One other issue issue is that video games are generally serious naturally with the major focus on studying rather than leisure. Although, we have an entertainment factor to keep your sons or daughters engaged, every game is frequently designed to work with a specific set of skills or programs, such as math concepts or science. Thanks for your posting.

  15. It is indeed my belief that mesothelioma will be the most deadly cancer. It’s got unusual attributes. The more I really look at it the greater I am convinced it does not conduct itself like a true solid cells cancer. In the event mesothelioma can be a rogue virus-like infection, therefore there is the chance of developing a vaccine along with offering vaccination for asbestos exposed people who are really at high risk regarding developing foreseeable future asbestos relevant malignancies. Thanks for discussing your ideas on this important health issue.

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

  17. Very nice post. I just stumbled upon your blog and wished to say that I’ve really enjoyed surfing around your blog posts. In any case I?ll be subscribing to your rss feed and I hope you write again very soon!

  18. This will be a terrific site, could you be interested in doing an interview about just how you created it? If so e-mail me!

  19. Thanks for the strategies presented. One thing I additionally believe is always that credit cards offering a 0 apr often attract consumers with zero monthly interest, instant authorization and easy on-line balance transfers, nonetheless beware of the main factor that may void the 0 easy street annual percentage rate and throw one out into the very poor house quickly.

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

  21. Have you ever thought about including a little bit more than just your articles? I mean, what you say is valuable and all. However imagine if you added some great graphics or videos to give your posts more, “pop”! Your content is excellent but with images and video clips, this website could undeniably be one of the greatest in its field. Terrific blog!

  22. Excellent website. Lots of useful info here. I am sending it to several friends ans also sharing in delicious. And obviously, thanks for your effort!

  23. Thanks for your post. Another factor is that being a photographer involves not only problems in recording award-winning photographs but hardships in acquiring the best digicam suited to your needs and most especially hardships in maintaining the quality of your camera. This can be very accurate and clear for those photography addicts that are in to capturing this nature’s exciting scenes – the mountains, the forests, the actual wild or maybe the seas. Going to these daring places unquestionably requires a digital camera that can live up to the wild’s hard natural environment.

  24. What?s Taking place i am new to this, I stumbled upon this I have found It positively useful and it has aided me out loads. I hope to give a contribution & help different users like its helped me. Good job.

  25. whoah this blog is great i love reading your posts. Stay up the good paintings! You know, a lot of individuals are looking around for this info, you could aid them greatly.

  26. In accordance with my observation, after a foreclosures home is available at a bidding, it is common for that borrower to still have some sort ofthat remaining unpaid debt on the mortgage. There are many financial institutions who seek to have all rates and liens cleared by the upcoming buyer. Even so, depending on selected programs, legislation, and state laws and regulations there may be a few loans which aren’t easily settled through the shift of loans. Therefore, the responsibility still rests on the lender that has got his or her property in foreclosure. Thank you for sharing your opinions on this blog.

  27. Wow that was unusual. I just wrote an extremely long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say wonderful blog!

發佈留言

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