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

35,136 Responses

  1. Another thing I’ve noticed is for many people, below-average credit is the consequence of circumstances outside of their control. For example they may be really saddled through an illness and because of this they have excessive bills going to collections. It may be due to a occupation loss or inability to go to work. Sometimes separation and divorce can send the money in an opposite direction. Thanks for sharing your ideas on this web site.

  2. Hello there, I found your site by the use of Google at the same time as looking for a similar matter, your site got here up, it appears good. I have bookmarked it in my google bookmarks.

  3. farm tires表示:

    I am so grateful for your blog article.Really thank you! Keep writing.

  4. VictorVal表示:

    olympe casino cresus: olympe casino avis – olympe casino cresus

  5. A further issue is that video gaming has become one of the all-time most significant forms of excitement for people of various age groups. Kids engage in video games, plus adults do, too. Your XBox 360 is just about the favorite gaming systems for folks who love to have a lot of games available to them, along with who like to relax and play live with some others all over the world. Thanks for sharing your thinking.

  6. Gregoryron表示:

    olympe: olympe casino – olympe casino cresus

  7. I’m curious to find out what blog platform you are using? I’m experiencing some small security problems with my latest site and I’d like to find something more risk-free. Do you have any suggestions?

  8. VictorVal表示:

    olympe casino: olympe casino – casino olympe

  9. Ronaldbet表示:

    casino olympe olympe casino cresus

  10. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:ремонт крупногабаритной техники в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  11. замена нагревательного элемента в стиральной машине aeg замена реле холодильника aeg

  12. Gregoryron表示:

    casino olympe: olympe casino cresus – olympe casino

  13. VictorVal表示:

    olympe casino en ligne: olympe casino cresus – olympe casino avis

  14. Gregoryron表示:

    olympe casino: olympe casino cresus – olympe casino

  15. Hi there just wanted to give you a quick heads up. The text in your post seem to be running off the screen in Safari. I’m not sure if this is a format issue or something to do with web browser compatibility but I figured I’d post to let you know. The style and design look great though! Hope you get the problem solved soon. Kudos

  16. Good write-up, I am regular visitor of one?s site, maintain up the excellent operate, and It is going to be a regular visitor for a lengthy time.

  17. I beloved up to you’ll obtain carried out proper here. The comic strip is tasteful, your authored subject matter stylish. nevertheless, you command get bought an edginess over that you want be turning in the following. in poor health surely come more previously once more since precisely the similar just about very ceaselessly within case you protect this hike.

  18. Oh my goodness! a tremendous article dude. Thank you Nevertheless I am experiencing issue with ur rss . Don?t know why Unable to subscribe to it. Is there anybody getting similar rss downside? Anybody who knows kindly respond. Thnkx

  19. VictorVal表示:

    olympe casino cresus: olympe casino en ligne – olympe casino en ligne

  20. Now I am going away to do my breakfast, after having my breakfast coming again toread other news.

  21. I do not even know how I ended up here, but I thought this post was good. I do not know who you are but definitely you are going to a famous blogger if you aren’t already 😉 Cheers!

  22. I’m in awe of the author’s ability to make complicated concepts understandable to readers of all backgrounds. This article is a testament to his expertise and commitment to providing useful insights. Thank you, author, for creating such an captivating and illuminating piece. It has been an incredible joy to read!

  23. Ronaldbet表示:

    olympe olympe casino cresus

  24. Admiring the time and energy you put into your site and detailed information you present. It’s good to come across a blog every once in a while that isn’t the same old rehashed material. Great read! I’ve bookmarked your site and I’m including your RSS feeds to my Google account.

  25. An impressive share, I simply given this onto a colleague who was doing a bit of analysis on this. And he in fact bought me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the deal with! However yeah Thnkx for spending the time to discuss this, I feel strongly about it and love studying extra on this topic. If attainable, as you develop into expertise, would you thoughts updating your weblog with more particulars? It is extremely useful for me. Large thumb up for this blog publish!

  26. I was suggested this web site by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my trouble. You’re amazing! Thanks!

  27. Hello.This article was really fascinating, especially since I was browsing for thoughts on this topic last Wednesday.

  28. Gregoryron表示:

    olympe casino: olympe casino avis – olympe casino en ligne

  29. Hello there, You’ve done an incredible job. I will definitely digg it and in my view suggest to my friends. I’m confident they’ll be benefited from this website.

  30. great post, very informative. I wonder why the other specialists of this sector don’t notice this. You should continue your writing. I am sure, you have a great readers’ base already!

發佈回覆給「Top Sightseeing Activities in Whistler」的留言 取消回覆

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