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

34,867 Responses

  1. 누누티비表示:

    Thanks for the strategies you have discussed here. Furthermore, I believe there are many factors which keep your car insurance policy premium down. One is, to consider buying cars that are within the good directory of car insurance organizations. Cars that are expensive are definitely more at risk of being snatched. Aside from that insurance is also in line with the value of your car, so the more costly it is, then higher the actual premium you only pay.

  2. 누누티비表示:

    Thanks for the recommendations on credit repair on this particular site. A few things i would advice people is always to give up the actual mentality they will buy at this point and fork out later. Like a society we tend to make this happen for many factors. This includes vacations, furniture, in addition to items we want. However, you’ll want to separate your current wants out of the needs. When you are working to improve your credit score you really have to make some trade-offs. For example it is possible to shop online to save cash or you can look at second hand stores instead of costly department stores to get clothing.

  3. Williszew表示:

    https://indiamedfast.com/# online medicine shopping in india

  4. JamesGag表示:

    mexican drug stores online: reliable mexican pharmacies – mexican pharmacy online order

  5. Тут можно преобрести навес для машины из поликарбоната в Санкт-Петербурге подробно на сайте навес на даче

  6. Holocaust表示:

    Cześć! Zapraszamy na oficjalną legalny stronę internetową Casino Vavada dla polskich graczy! Oferujemy bogaty wybór gier kasynowych od 44 uznanych twórców, takich jak Truelab, Pragmatic Play, IGT, Endorphina, Evolution Gaming, Playtech czy BGaming. Nasz program lojalnościowy obejmuje 5 poziomów członkostwa (od początkującego aż po platynowego), a w sekcji z grami na żywo możesz doświadczyć emocji dzięki profesjonalnym krupierom.

  7. Gestapo表示:

    Cześć! Zapraszamy na oficjalną legalny stronę internetową Casino Vavada dla polskich graczy! Oferujemy bogaty wybór gier kasynowych od 44 uznanych twórców, takich jak Truelab, Pragmatic Play, IGT, Endorphina, Evolution Gaming, Playtech czy BGaming. Nasz program lojalnościowy obejmuje 5 poziomów członkostwa (od początkującego aż po platynowego), a w sekcji z grami na żywo możesz doświadczyć emocji dzięki profesjonalnym krupierom.

  8. Cześć! Zapraszamy na oficjalną legalny stronę internetową Casino Vavada dla polskich graczy! Oferujemy bogaty wybór gier kasynowych od 44 uznanych twórców, takich jak Truelab, Pragmatic Play, IGT, Endorphina, Evolution Gaming, Playtech czy BGaming. Nasz program lojalnościowy obejmuje 5 poziomów członkostwa (od początkującego aż po platynowego), a w sekcji z grami na żywo możesz doświadczyć emocji dzięki profesjonalnym krupierom.

  9. gay sex表示:

    Cześć! Zapraszamy na oficjalną legalny stronę internetową Casino Vavada dla polskich graczy! Oferujemy bogaty wybór gier kasynowych od 44 uznanych twórców, takich jak Truelab, Pragmatic Play, IGT, Endorphina, Evolution Gaming, Playtech czy BGaming. Nasz program lojalnościowy obejmuje 5 poziomów członkostwa (od początkującego aż po platynowego), a w sekcji z grami na żywo możesz doświadczyć emocji dzięki profesjonalnym krupierom.

  10. Thanks for sharing excellent informations. Your website is so cool. I’m impressed by the details that you have on this blog. It reveals how nicely you understand this subject. Bookmarked this website page, will come back for extra articles. You, my friend, ROCK! I found just the information I already searched all over the place and just couldn’t come across. What a great web-site.

  11. Georgetwiva表示:

    informative post zkLogin

  12. Тут можно преобрести навесы для машины в Санкт-Петербурге подробно на сайте навес из поликарбоната для дачи

  13. My programmer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the expenses. But he’s tryiong none the less. I’ve been using WordPress on various websites for about a year and am concerned about switching to another platform. I have heard great things about blogengine.net. Is there a way I can transfer all my wordpress posts into it? Any help would be really appreciated!

  14. Тут можно преобрести навес из поликарбоната для дачи в Санкт-Петербурге подробно на сайте навес для автомобиля купить

  15. Josephsip表示:

    alo789: alo 789 dang nh?p – 789alo

  16. Тут можно преобрести навес перед домом для машины в Санкт-Петербурге подробно на сайте навес двухскатный

  17. Hello! Do you know if they make any plugins to help with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results. If you know of any please share. Thanks!

  18. you’re truly a good webmaster. The site loading velocity is amazing. It sort of feels that you’re doing any distinctive trick. Also, The contents are masterwork. you’ve performed a excellent job on this subject!

  19. Josephsip表示:

    alo789: 789alo – alo789 dang nh?p

  20. Rubengax表示:

    k8 th? dam k8 th? dam k8 th? dam

  21. Thank you for some other informative blog. Where else could I am getting that kind of info written in such an ideal way? I have a project that I’m just now operating on, and I have been at the glance out for such information.

發佈回覆給「kèo nhà cái」的留言 取消回覆

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