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

  1. I’ve been surfing online more than 3 hours today, yet I never found any interesting article like yours. It?s pretty worth enough for me. Personally, if all site owners and bloggers made good content as you did, the internet will be much more useful than ever before.

  2. 強 訓読み表示:

    During difficult times, having a help system in place can make a significant distinction in an individual’s skill to cope and bounce again.

  3. I’m in awe of the author’s capability to make complex concepts approachable 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 engaging and illuminating piece. It has been an absolute pleasure to read!

  4. One thing I’ve noticed is always that there are plenty of common myths regarding the lenders intentions any time talking about property foreclosures. One delusion in particular would be the fact the bank wants your house. The bank wants your hard earned cash, not your own home. They want the amount of money they lent you with interest. Preventing the bank is only going to draw the foreclosed realization. Thanks for your write-up.

  5. Fascinating blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple adjustements would really make my blog stand out. Please let me know where you got your theme. Thanks

  6. Hello, Neat post. There is an issue along with your web site in internet explorer, would test this? IE nonetheless is the marketplace chief and a huge element of other people will pass over your excellent writing due to this problem.

  7. I know this if off topic but I’m looking into starting my own blog and was curious what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet savvy so I’m not 100 positive. Any tips or advice would be greatly appreciated. Thank you

  8. The subsequent time I read a weblog, I hope that it doesnt disappoint me as much as this one. I imply, I do know it was my choice to learn, but I really thought youd have one thing attention-grabbing to say. All I hear is a bunch of whining about something that you could possibly fix if you werent too busy searching for attention.

  9. One thing I would really like to discuss is that weightloss routine fast is possible by the right diet and exercise. People’s size not only affects appearance, but also the quality of life. Self-esteem, major depression, health risks, plus physical ability are affected in weight gain. It is possible to just make everything right but still gain. In such a circumstance, a medical problem may be the offender. While too much food rather than enough exercise are usually to blame, common medical ailments and widespread prescriptions could greatly help to increase size. I am grateful for your post right here.

  10. Hi there, You have done a great job. I?ll definitely digg it and personally recommend to my friends. I am sure they’ll be benefited from this web site.

  11. Does your site have a contact page? I’m having problems locating it but, I’d like to shoot you an e-mail. I’ve got some creative ideas for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it improve over time.

  12. What i do not realize is actually how you’re not really much more well-liked than you might be right now. You’re very intelligent. You realize therefore significantly relating to this subject, made me personally consider it from a lot of varied angles. Its like women and men aren’t fascinated unless it?s one thing to accomplish with Lady gaga! Your own stuffs nice. Always maintain it up!

  13. I have noticed that fees for online degree experts tend to be an awesome value. For instance a full 4-year college Degree in Communication in the University of Phoenix Online consists of Sixty credits at $515/credit or $30,900. Also American Intercontinental University Online makes available Bachelors of Business Administration with a total school feature of 180 units and a price of $30,560. Online studying has made obtaining your college degree far more easy because you could earn your own degree from the comfort in your home and when you finish from work. Thanks for other tips I have certainly learned from your web site.

  14. RobertGlolf表示:

    [url=https://lisotvet.ru/wp-content/pages/bk_pari_promokod_na_fribet_bonus_do_25000_rubley.html]пари бэт промокод[/url]

  15. I?ll right away grab your rss as I can not in finding your email subscription hyperlink or newsletter service. Do you have any? Kindly permit me recognise in order that I could subscribe. Thanks.

  16. There’s noticeably a bundle to know about this. I assume you made certain good factors in features also.

  17. That fingerprint represents the digital equivalent of a pink flag — when a computer system is aware of how to interpret its message, it acts as a warning that says “I am copyrighted!” Of course, it isn’t quite that simple.

  18. Larryenern表示:

    Промокод Фонбет – это кодовые слова, например: MAX777, ввод которых при регистрации в БК Фонбет или в личном кабинете позволяет получить фрибеты, страховки ставок и другие специальные бонусы. Промокодом в беттинге называется комбинация букв и цифр, при вводе которых активируется бонус. Новым клиентам Фонбет предлагает приветственные фрибеты на сумму от 100 до 15 000 рублей.

    промокод на фонбет на сегодня действующий

  19. Undeniably believe that which you stated. Your favorite reason seemed to be on the web the easiest thing to be aware of. I say to you, I definitely get annoyed while people think about worries that they just do not know about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks

發佈回覆給「Larryenern」的留言 取消回覆

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