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

38,088 Responses

  1. Bernardshoor表示:

    п»їpharmacie en ligne france: Pharmacies en ligne certifiees – pharmacie en ligne sans ordonnance pharmafst.com

  2. Peterclada表示:

    Tadalafil achat en ligne Pharmacie en ligne Cialis sans ordonnance Acheter Viagra Cialis sans ordonnance tadalmed.com

  3. I have witnessed that intelligent real estate agents almost everywhere are Advertising and marketing. They are knowing that it’s more than merely placing a sign post in the front yard. It’s really in relation to building human relationships with these traders who at some point will become purchasers. So, while you give your time and energy to encouraging these suppliers go it alone — the “Law associated with Reciprocity” kicks in. Great blog post.

  4. BradleyJaire表示:

    cialis prix: cialis sans ordonnance – cialis generique tadalmed.shop

  5. Robertfap表示:

    http://pharmafst.com/# acheter mГ©dicament en ligne sans ordonnance

  6. I have observed that over the course of making a relationship with real estate entrepreneurs, you’ll be able to come to understand that, in most real estate contract, a commission is paid. Eventually, FSBO sellers really don’t “save” the payment. Rather, they struggle to earn the commission by means of doing the agent’s job. In the process, they commit their money plus time to carry out, as best they could, the assignments of an real estate agent. Those tasks include exposing the home by means of marketing, representing the home to prospective buyers, constructing a sense of buyer emergency in order to prompt an offer, making arrangement for home inspections, dealing with qualification investigations with the financial institution, supervising maintenance, and facilitating the closing.

  7. Peterclada表示:

    Cialis en ligne cialis sans ordonnance Acheter Viagra Cialis sans ordonnance tadalmed.com

  8. BillieLet表示:

    Acheter Cialis 20 mg pas cher: Cialis sans ordonnance 24h – Tadalafil achat en ligne tadalmed.shop

  9. A lot of of whatever you state happens to be supprisingly legitimate and that makes me ponder why I had not looked at this with this light previously. This piece really did turn the light on for me as far as this subject goes. But at this time there is 1 issue I am not really too comfy with so while I make an effort to reconcile that with the actual main idea of the position, allow me observe just what the rest of the readers have to say.Very well done.

  10. Aw, this was a really nice post. In idea I wish to put in writing like this additionally ? taking time and actual effort to make a very good article? however what can I say? I procrastinate alot and not at all seem to get something done.

  11. Hmm it appears like your blog ate my first comment (it was super long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I too am an aspiring blog blogger but I’m still new to everything. Do you have any tips and hints for novice blog writers? I’d definitely appreciate it.

  12. I think one of your ads triggered my web browser to resize, you may well want to put that on your blacklist.

  13. BillieLet表示:

    Cialis sans ordonnance 24h: cialis prix – Tadalafil 20 mg prix en pharmacie tadalmed.shop

  14. Robertfap表示:

    https://kamagraprix.com/# Achetez vos kamagra medicaments

  15. Throughout the great scheme of things you secure an A+ just for hard work. Where exactly you misplaced everybody was on the details. You know, as the maxim goes, details make or break the argument.. And it could not be much more true here. Having said that, let me inform you exactly what did do the job. The text can be really persuasive which is probably why I am making an effort to comment. I do not really make it a regular habit of doing that. 2nd, whilst I can certainly notice the jumps in reasoning you make, I am not convinced of how you seem to unite the ideas which inturn produce the conclusion. For the moment I shall yield to your issue however hope in the future you actually link your facts better.

  16. JesseHef表示:

    Josh Giddey hits halfcourt buzzer-beater over LeBron James to cap wild finale as the Bulls stun the Lakers
    quickswap exchange
    Josh Giddey hit a game-winning, halfcourt buzzer-beater over LeBron James as the Chicago Bulls stunned the Los Angeles Lakers in one of the wildest endings to an NBA game you are ever likely to see.

    Trailing 115-110 with 12.6 seconds remaining, Giddey’s inbound pass found Nikola Vucevic, who pushed the ball to a wide-open Patrick Williams for a corner three-pointer.

    James then fluffed the Lakers inbound pass from the baseline, allowing Giddey to steal the ball and find Coby White for a second Bulls triple in quick succession to put Chicago up 116-115 with 6.1 seconds remaining.
    Austin Reaves then made a driving layup to put the Lakers ahead 117-116 with 3.3 seconds left, but the game wasn’t done yet.

    With no timeouts remaining, Giddey inbounded the ball to Williams from the baseline, got the pass back, took one dribble and launched a shot from beyond halfcourt.

    Supporters in the stands seemed frozen in anticipation as the ball sailed through the air, and the United Center then erupted as it fell through the net. After the dramatic win, Giddey found himself being swarmed by his teammates.

    “Special moment to do it with these guys, this team,” Giddey said, per ESPN. “We’ve shown over the last month to six weeks that we can beat anybody. The way we play the game, I think it wears people down.

    “We get up and down. We run. We put heat on them to get back. A lot of veteran teams don’t particularly want to get back and play in transition.”

    Giddey later told the Bulls broadcast that he’d “never made a game-winner before.”

    The ending capped an incredible couple of games for the Lakers, who had themselves won their last game against the Indiana Pacers on Wednesday with a buzzer-beating tip-in from James.

  17. Wonderful goods from you, man. I’ve understand your stuff previous to and you are just extremely wonderful. I really like what you have acquired here, really like what you’re stating and the way in which you say it. You make it enjoyable and you still care for to keep it smart. I can not wait to read far more from you. This is actually a great web site.

  18. Peterclada表示:

    Cialis generique prix Cialis generique prix Tadalafil 20 mg prix sans ordonnance tadalmed.com

  19. Bernardshoor表示:

    trouver un mГ©dicament en pharmacie: pharmacie en ligne sans ordonnance – vente de mГ©dicament en ligne pharmafst.com

  20. Thanks for every other informative website. The place else may just I get that type of info written in such an ideal way? I’ve a project that I am just now working on, and I have been at the look out for such information.

  21. BradleyJaire表示:

    Pharmacie Internationale en ligne: Meilleure pharmacie en ligne – pharmacie en ligne pas cher pharmafst.com

  22. Wow that was strange. I just wrote an extremely long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyhow, just wanted to say excellent blog!

  23. Nice read, I just passed this onto a friend who was doing some research on that. And he actually bought me lunch because I found it for him smile Therefore let me rephrase that: Thank you for lunch!

  24. Heya i am for the primary time here. I came across this board and I to find It really useful & it helped me out a lot. I am hoping to give something back and help others like you helped me.

  25. This design is incredible! You certainly know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!

  26. Nearly all of whatever you state happens to be supprisingly legitimate and it makes me ponder the reason why I had not looked at this in this light previously. Your piece truly did switch the light on for me as far as this issue goes. However there is actually one particular position I am not really too cozy with so whilst I attempt to reconcile that with the actual core idea of the position, allow me see exactly what all the rest of your visitors have to say.Well done.

  27. BradleyJaire表示:

    Kamagra pharmacie en ligne: Achetez vos kamagra medicaments – achat kamagra

  28. Prokarniz表示:

    Освободитесь от рутины с автоматикой Somfy
    Автоматика Somfy Автоматика Somfy . Prokarniz

  29. I have mastered some new elements from your web site about personal computers. Another thing I’ve always believed is that laptop computers have become an item that each household must have for some reasons. They offer convenient ways in which to organize the home, pay bills, go shopping, study, tune in to music and in some cases watch shows. An innovative way to complete every one of these tasks is a laptop. These personal computers are mobile, small, powerful and lightweight.

  30. I do agree with all the ideas you have presented in your post. They are really convincing and will definitely work. Still, the posts are very short for novices. Could you please extend them a bit from next time? Thanks for the post.

發佈回覆給「บอลสเต็ป SBOBET」的留言 取消回覆

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