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

  1. DouglasGed表示:

    how to get ed pills: Cheap ED pills online – how to get ed meds online

  2. DouglasGed表示:

    mexican mail order pharmacies: Mexico pharmacy online – purple pharmacy mexico price list

  3. hello there and thank you for your information ? I have certainly picked up something new from right here. I did however expertise some technical issues using this website, since I experienced to reload the website 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 very frequently affect your placement in google and could damage your high quality score if ads and marketing with Adwords. Well I?m adding this RSS to my e-mail and can look out for much more of your respective exciting content. Ensure that you update this again very soon..

  4. I believe that avoiding refined foods is a first step in order to lose weight. They could taste great, but refined foods include very little vitamins and minerals, making you take more simply to have enough power to get with the day. If you are constantly consuming these foods, transferring to whole grains and other complex carbohydrates will help you to have more energy while ingesting less. Good blog post.

  5. Thanks for your publication on the travel industry. I might also like contribute that if you’re a senior taking into consideration traveling, it can be absolutely essential that you buy travel cover for retirees. When traveling, senior citizens are at greatest risk being in need of a health care emergency. Obtaining the right insurance policies package for your age group can safeguard your health and provide peace of mind.

  6. Can I simply say what a aid to search out someone who really is aware of what theyre speaking about on the internet. You undoubtedly know how you can convey a problem to mild and make it important. Extra individuals need to learn this and understand this side of the story. I cant consider youre not more in style since you positively have the gift.

  7. Also I believe that mesothelioma cancer is a rare form of most cancers that is normally found in those people previously exposed to asbestos. Cancerous tissue form in the mesothelium, which is a shielding lining which covers the vast majority of body’s body organs. These cells typically form in the lining from the lungs, stomach, or the sac which encircles one’s heart. Thanks for expressing your ideas.

  8. I have realized that over the course of making a relationship with real estate managers, you’ll be able to get them to understand that, in each and every real estate contract, a payment is paid. Ultimately, FSBO sellers will not “save” the fee. Rather, they struggle to win the commission by doing a agent’s occupation. In completing this task, they commit their money in addition to time to conduct, as best they will, the tasks of an representative. Those jobs include uncovering the home by way of marketing, showing the home to all buyers, constructing a sense of buyer desperation in order to make prompt an offer, arranging home inspections, dealing with qualification investigations with the loan provider, supervising maintenance tasks, and assisting the closing.

  9. Youre so cool! I dont suppose Ive learn anything like this before. So nice to find anyone with some original ideas on this subject. realy thank you for starting this up. this web site is something that’s needed on the web, someone with just a little originality. helpful job for bringing one thing new to the internet!

  10. Hey there! 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 problems finding one? Thanks a lot!

  11. I really appreciate this post. I have been looking everywhere for this! Thank goodness I found it on Bing. You have made my day! Thx again

  12. Hqwnwr表示:

    deflazacort usa – cheap calcort sale alphagan price

  13. There’s noticeably a bundle to learn about this. I assume you made certain good points in features also.

  14. Leonardpar表示:

    https://mexicopharmacy.win/# purple pharmacy mexico price list

  15. Leonardpar表示:

    https://edpillpharmacy.store/# discount ed pills

  16. DouglasGed表示:

    mexican pharmaceuticals online: Best pharmacy in Mexico – mexican pharmaceuticals online

  17. DouglasGed表示:

    cheap ed: Cheapest online ED treatment – get ed meds online

  18. DouglasGed表示:

    pharmacies in mexico that ship to usa: Medicines Mexico – pharmacies in mexico that ship to usa

  19. Check out my web page: Daycare Near Me (http://temausallc.com)

  20. Yrefrzl表示:

    Привет!
    Приобрести диплом ВУЗа.
    serggrub.blogspot.com/2015/03/Chto-luchshe-vybrat-LIveJournal-ili-Blogger

  21. Meeting with local real estate agents will give you a much more encompassing view of the available properties for investment opportunities.

  22. Yesterday, while I was at work, my cousin stole my apple ipad and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is totally off topic but I had to share it with someone!

  23. Great goods from you, man. I’ve understand your stuff previous to and you are just too fantastic. I actually like what you’ve acquired here, really like what you’re saying and the way in which you say it. You make it entertaining and you still care for to keep it wise. I can not wait to read far more from you. This is really a wonderful site.

  24. Leonardpar表示:

    https://mexicopharmacy.win/# mexican border pharmacies shipping to usa

  25. Trefntq表示:

    Привет, друзья!
    Легальные способы покупки диплома о среднем полном образовании
    filippwhite.blogspot.ru/2015/06/blog-post
    Всегда вам поможем!.

  26. Great beat ! I would like to apprentice while you amend your web site, how can i subscribe for a blog web site? The account helped me a acceptable deal. I had been tiny bit acquainted of this your broadcast offered bright clear idea

  27. I would like to thnkx for the efforts you’ve put in writing this site. I am hoping the same high-grade web site post from you in the upcoming also. Actually your creative writing abilities has inspired me to get my own site now. Really the blogging is spreading its wings fast. Your write up is a great example of it.

  28. Hello! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My site looks weird when viewing from my iphone. I’m trying to find a template or plugin that might be able to correct this issue. If you have any suggestions, please share. Appreciate it!

  29. You can also make provisions for the fulfillment of short-term dreams: the next vacation, a new mobile phone or a training course, for example.

  30. Danielreame表示:

    Betfair Casino Espana
    betfair app casino
    Si estas en la busqueda de un casino online en Espana que ofrezca fiabilidad, podria ser la opcion perfecta. Con licencia y cumpliendo con los mas altos estandares de seguridad, este casino destaca por su variada seleccion de juegos proporcionados por los mas renombrados desarrolladores a nivel mundial. Desde tragamonedas clasicas hasta envolventes juegos de casino en vivo, Betfair Casino se ha convertido en el destino favorito de numerosos jugadores espanoles. Descubre en nuestra resena por que Betfair Casino ha logrado captar la atencion de tantos usuarios y conoce en detalle las caracteristicas que lo hacen destacar en el sector.
    Resena sobre Betfair Casino Espana
    Betfair Casino se ha establecido firmemente en el mercado de juegos de azar espanol como una opcion de confianza para los entusiastas del casino online. Operado por Betfair Casino Limited, este sitio esta acreditado por la Comision de Juegos del Reino Unido y la Autoridad de Juegos de Malta, ofreciendo un ambiente de juego seguro y regulado. A continuacion, te proporcionamos informacion relevante sobre Betfair Casino en Espana.

發佈留言

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