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

  1. apk download表示:

    I’m really enjoying the design and layout of your website. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a designer to create your theme? Superb work!

  2. Victorprima表示:

    Always leaving this place satisfied.
    gabapentin 300 principio attivo
    A place where customer health is the top priority.

  3. One more important area is that if you are a senior citizen, travel insurance regarding pensioners is something you need to really take into consideration. The older you are, a lot more at risk you happen to be for getting something undesirable happen to you while in foreign countries. If you are not covered by a few comprehensive insurance policy, you could have a number of serious challenges. Thanks for expressing your advice on this blog.

  4. 66 c表示:

    One other thing I would like to talk about is that instead of trying to match all your online degree classes on days of the week that you complete work (considering that people are tired when they get back), try to obtain most of your classes on the saturdays and sundays and only 1 or 2 courses for weekdays, even if it means a little time off your saturday and sunday. This is fantastic because on the week-ends, you will be a lot more rested plus concentrated upon school work. Thanks a lot for the different ideas I have realized from your web site.

  5. WalterCherm表示:

    What side effects can this medication cause?
    https://cytotecpharm24.top/
    They stock quality medications from all over the world.

  6. DonaldTyclE表示:

    analizador de vibraciones
    Equipos de calibración: fundamental para el operación uniforme y óptimo de las maquinarias.

    En el entorno de la avances avanzada, donde la productividad y la seguridad del aparato son de suma trascendencia, los equipos de balanceo cumplen un rol vital. Estos dispositivos específicos están desarrollados para balancear y fijar elementos móviles, ya sea en maquinaria productiva, transportes de transporte o incluso en equipos caseros.

    Para los expertos en reparación de sistemas y los ingenieros, trabajar con dispositivos de equilibrado es crucial para promover el funcionamiento estable y confiable de cualquier mecanismo rotativo. Gracias a estas soluciones modernas avanzadas, es posible reducir notablemente las vibraciones, el sonido y la tensión sobre los rodamientos, prolongando la duración de componentes costosos.

    Asimismo trascendental es el papel que cumplen los equipos de ajuste en la atención al cliente. El soporte técnico y el mantenimiento constante utilizando estos sistemas posibilitan brindar prestaciones de gran estándar, aumentando la agrado de los clientes.

    Para los titulares de empresas, la inversión en equipos de ajuste y sensores puede ser esencial para aumentar la efectividad y desempeño de sus sistemas. Esto es principalmente relevante para los dueños de negocios que gestionan reducidas y modestas empresas, donde cada aspecto vale.

    Por otro lado, los dispositivos de equilibrado tienen una amplia utilización en el sector de la protección y el gestión de calidad. Habilitan identificar potenciales problemas, impidiendo intervenciones caras y daños a los dispositivos. Más aún, los datos extraídos de estos aparatos pueden aplicarse para perfeccionar métodos y mejorar la presencia en buscadores de investigación.

    Las sectores de uso de los dispositivos de balanceo cubren numerosas sectores, desde la manufactura de ciclos hasta el seguimiento de la naturaleza. No interesa si se habla de grandes fabricaciones productivas o pequeños establecimientos hogareños, los dispositivos de balanceo son fundamentales para garantizar un funcionamiento productivo y sin presencia de detenciones.

  7. Hi are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and create my own. Do you require any html coding knowledge to make your own blog? Any help would be greatly appreciated!

  8. 66 c表示:

    Thanks for your write-up. I would like to say that the very first thing you will need to complete is determine if you really need credit improvement. To do that you simply must get your hands on a copy of your credit report. That should not be difficult, since government makes it necessary that you are allowed to obtain one absolutely free copy of your own credit report on a yearly basis. You just have to inquire the right people today. You can either check out the website for your Federal Trade Commission or perhaps contact one of the main credit agencies immediately.

  9. Nice blog here! Also your website loads up very fast! What host are you using? Can I get your affiliate link to your host? I wish my website loaded up as quickly as yours lol

  10. WalterCherm表示:

    Their international shipment tracking system is top-notch.
    https://clomidpharm24.top/
    Speedy service with a smile!

  11. Thanks for your write-up. I would love to remark that the first thing you will need to conduct is to see if you really need credit score improvement. To do that you must get your hands on a replica of your credit report. That should really not be difficult, because government mandates that you are allowed to receive one free copy of your real credit report yearly. You just have to consult the right persons. You can either check out the website with the Federal Trade Commission or even contact one of the main credit agencies straight.

  12. Jasonzitte表示:

    A trailblazer in international pharmacy practices.
    can i buy generic lisinopril without insurance
    What side effects can this medication cause?

  13. Jasonzitte表示:

    Every international delivery is prompt and secure.
    will side effects of gabapentin go away
    A stalwart in international pharmacy services.

  14. apk download表示:

    You made some first rate points there. I appeared on the web for the problem and located most people will go together with together with your website.

  15. WalterCherm表示:

    Consistent service, irrespective of borders.
    https://lisinoprilpharm24.top/
    Always leaving this place satisfied.

  16. This is a fantastic web page, would you be interested in doing an interview about how you created it? If so e-mail me!

  17. 66 c表示:

    I?ve read several good stuff here. Definitely worth bookmarking for revisiting. I wonder how much effort you put to create such a wonderful informative web site.

  18. Victorprima表示:

    They consistently exceed global healthcare expectations.
    order clomid tablets
    They offer great recommendations on vitamins.

  19. Thanks for the tips on credit repair on this amazing web-site. The thing I would offer as advice to people would be to give up the particular mentality they can buy today and pay out later. As a society all of us tend to repeat this for many factors. This includes vacation trips, furniture, and items we would like. However, you have to separate the wants from all the needs. As long as you’re working to raise your credit ranking score you really have to make some trade-offs. For example you’ll be able to shop online to save cash or you can go to second hand retailers instead of pricey department stores pertaining to clothing.

  20. 66lottery表示:

    I believe that avoiding ready-made foods is the first step in order to lose weight. They can taste fine, but packaged foods contain very little nutritional value, making you take more only to have enough vigor to get throughout the day. When you are constantly ingesting these foods, switching to whole grains and other complex carbohydrates will help you have more strength while ingesting less. Interesting blog post.

  21. WalterCherm表示:

    Commonly Used Drugs Charts.
    https://gabapentinpharm24.top/
    A touchstone of international pharmacy standards.

  22. RileyBok表示:

    Viagra * Cialis * Levitra

    All the products you are looking for are currently close by for the duration of 1+1.

    4 more tablets of unified of the following services: Viagra * Cialis * Levitra

    https://pxman.net

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

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