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

10,797 Responses

  1. AnthonyPress表示:

    top 10 online pharmacy in india reputable indian pharmacies mail order pharmacy india

  2. Ngan表示:

    My web-site Daycare Near Me By State; Ngan,

  3. JeremyPsymn表示:

    http://easyrxcanada.com/# canadian pharmacy online

  4. Eugeneaftek表示:

    Tiny shards of plastic are increasingly infiltrating our brains, study says
    анальный секс первые
    Human brain samples collected at autopsy in early 2024 contained more tiny shards of plastic than samples collected eight years prior, according to a preprint posted online in May. A preprint is a study which has not yet been peer-reviewed and published in a journal.

    “The concentrations we saw in the brain tissue of normal individuals, who had an average age of around 45 or 50 years old, were 4,800 micrograms per gram, or 0.5% by weight,” said lead study author Matthew Campen, a regents’ professor of pharmaceutical sciences at the University of New Mexico in Albuquerque.
    “Compared to autopsy brain samples from 2016, that’s about 50% higher,” Campen said. “That would mean that our brains today are 99.5% brain and the rest is plastic.”

    That increase, however, only shows exposure and does not provide information about brain damage, said Phoebe Stapleton, an associate professor of pharmacology and toxicology at Rutgers University in Piscataway, New Jersey, who was not involved in the preprint.

    “It is unclear if, in life, these particles are fluid, entering and leaving the brain, or if they collect in neurological tissues and promote disease,” she said in an email. “Further research is needed to understand how the particles may be interacting with the cells and if this has a toxicological consequence.”

    The brain samples contained 7% to 30% more tiny shards of plastic than samples from the cadavers’ kidneys and liver, according to the preprint.

    “Studies have found these plastics in the human heart, the great blood vessels, the lungs, the liver, the testes, the gastrointestinal tract and the placenta,” said pediatrician and biology professor Dr. Philip Landrigan, director of the Program for Global Public Health and the Common Good and the Global Observatory on Planetary Health at Boston College.

    “It’s important not to scare the hell out of people, because the science in this space is still evolving, and nobody in the year 2024 is going to live without plastic,” said Landrigan, who was not involved with the preprint.

  5. Robertengep表示:

    https://mexstarpharma.com/# п»їbest mexican online pharmacies

  6. Dnrtcmp表示:

    Привет!
    Приобрести документ ВУЗа вы имеете возможность у нас в Москве.
    ok-vmeste.ru/toget/1459-zhelaete-zakazat-podlinnyi-diplom

  7. AnthonyPress表示:

    buying prescription drugs in mexico online mexican rx online mexico drug stores pharmacies

  8. Robertengep表示:

    https://easyrxcanada.online/# my canadian pharmacy rx

  9. Youre so cool! I dont suppose Ive read something like this before. So good to search out anyone with some authentic thoughts on this subject. realy thank you for beginning this up. this web site is something that’s needed on the internet, somebody with just a little originality. useful job for bringing something new to the internet!

  10. This article is absolutely incredible! The author has done a phenomenal job of conveying the information in an captivating and educational manner. I can’t thank him enough for offering such precious insights that have certainly enhanced my knowledge in this subject area. Bravo to him for crafting such a gem!

  11. Thanks for your post. I would love to say that the first thing you will need to carry out is determine whether you really need credit improvement. To do that you have got to get your hands on a replica of your credit history. That should not be difficult, since the government mandates that you are allowed to be issued one totally free copy of the credit report yearly. You just have to check with the right persons. You can either check out the website owned by the Federal Trade Commission or even contact one of the leading credit agencies right away.

  12. My brother suggested I may like this blog. He was entirely right. This post truly made my day. You can not consider simply how much time I had spent for this information! Thanks!

  13. I have learn a few excellent stuff here. Definitely worth bookmarking for revisiting. I wonder how a lot effort you put to make this kind of fantastic informative website.

  14. Heya i am for the first time here. I came across this board and I find It really useful & it helped me out a lot. I am hoping to give something back and aid others such as you aided me.

  15. I am very happy to read this. This is the type of manual that needs to be given and not the random misinformation that’s at the other blogs. Appreciate your sharing this greatest doc.

  16. I loved as much as you’ll receive carried out right here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get bought an edginess over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you shield this hike.

  17. You could definitely see your skills in the work you write. The world hopes for more passionate writers like you who are not afraid to say how they believe. Always go after your heart.

  18. One more thing. I really believe that there are a lot of travel insurance web sites of dependable companies that permit you to enter your journey details and obtain you the quotations. You can also purchase the particular international holiday insurance policy on internet by using the credit card. All you need to do is always to enter the travel particulars and you can view the plans side-by-side. You only need to find the package that suits your financial budget and needs and use your bank credit card to buy the idea. Travel insurance online is a good way to do investigation for a trustworthy company regarding international travel cover. Thanks for sharing your ideas.

  19. I have recently started a site, the info you provide on this site has helped me tremendously. Thanks for all of your time & work.

  20. I know this if off topic but I’m looking into starting my own blog and was curious what all is required to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web savvy so I’m not 100 certain. Any tips or advice would be greatly appreciated. Appreciate it

  21. Thanks for giving your ideas listed here. The other thing is that when a problem occurs with a pc motherboard, people should not have some risk regarding repairing it themselves for if it is not done right it can lead to irreparable damage to the whole laptop. Most commonly it is safe just to approach the dealer of a laptop for your repair of motherboard. They’ve technicians with an knowledge in dealing with laptop motherboard challenges and can get the right diagnosis and undertake repairs.

  22. I’m not that much of a online reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your site to come back later on. Many thanks

  23. I’m often to running a blog and i actually respect your content. The article has actually peaks my interest. I am going to bookmark your web site and keep checking for brand spanking new information.

  24. Would you be interested in exchanging links?

  25. Aw, this was a very nice post. In idea I would like to put in writing like this moreover ? taking time and precise effort to make a very good article? however what can I say? I procrastinate alot and not at all appear to get one thing done.

  26. Hello! I’ve been reading your web site for some time now and finally got the bravery to go ahead and give you a shout out from Atascocita Tx! Just wanted to say keep up the fantastic work!

  27. Great goods from you, man. I have understand your stuff previous to and you’re just extremely magnificent. I actually like what you have acquired here, really 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 sensible. I can not wait to read far more from you. This is really a terrific website.

  28. I would also like to add that in case you do not surely have an insurance policy or perhaps you do not participate in any group insurance, chances are you’ll well gain from seeking the aid of a health insurance agent. Self-employed or those with medical conditions generally seek the help of the health insurance broker. Thanks for your article.

  29. Robertengep表示:

    https://easyrxindia.shop/# indianpharmacy com

發佈留言

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