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

35,036 Responses

  1. 늑대닷컴表示:

    Thanks for the write-up. My partner and i have constantly observed that almost all people are needing to lose weight since they wish to look slim plus attractive. Nonetheless, they do not continually realize that there are additional benefits to losing weight in addition. Doctors insist that overweight people have problems with a variety of health conditions that can be instantly attributed to their particular excess weight. The great thing is that people who sadly are overweight and suffering from a variety of diseases are able to reduce the severity of their illnesses by means of losing weight. It is easy to see a constant but noticeable improvement with health when even a negligible amount of fat reduction is attained.

  2. 늑대닷컴表示:

    One thing I’d like to say is before buying more personal computer memory, have a look at the machine into which it could well be installed. If the machine is usually running Windows XP, for instance, the particular memory limit is 3.25GB. Putting in more than this would merely constitute any waste. Make certain that one’s motherboard can handle your upgrade amount, as well. Interesting blog post.

  3. 늑대닷컴表示:

    Nearly all of the things you say is astonishingly legitimate and it makes me ponder the reason why I had not looked at this in this light previously. This piece really did turn the light on for me personally as far as this subject goes. But there is one factor I am not really too cozy with and while I attempt to reconcile that with the actual central idea of the point, let me see exactly what the rest of the subscribers have to say.Very well done.

  4. 늑대닷컴表示:

    Great beat ! I wish to apprentice while you amend your site, how can i subscribe for a weblog web site? The account aided me a appropriate deal. I had been tiny bit acquainted of this your broadcast offered bright transparent concept

  5. 늑대닷컴表示:

    Thanks for these tips. One thing I should also believe is that often credit cards presenting a 0 monthly interest often entice consumers together with zero rate of interest, instant endorsement and easy over-the-internet balance transfers, but beware of the most recognized factor that will certainly void your current 0 easy road annual percentage rate as well as throw anybody out into the very poor house rapidly.

  6. Michaeltor表示:

    Apoteket online: apotek online recept – Apoteket online

  7. 늑대닷컴表示:

    whoah this blog is fantastic i really like reading your articles. Stay up the great work! You understand, many people are searching around for this information, you can aid them greatly.

  8. HomerFaw表示:

    https://apotekonlinerecept.shop/# apotek online recept

  9. 늑대닷컴表示:

    I think this is among the such a lot important info for me. And i am satisfied reading your article. But should statement on some general issues, The site style is great, the articles is really excellent : D. Just right process, cheers

  10. Michaeltor表示:

    apotek pa nett: apotek online recept – apotek online recept

  11. DonaldTyclE表示:

    vibracion de motor
    Dispositivos de calibracion: fundamental para el desempeno fluido y efectivo de las maquinas.

    En el entorno de la avances avanzada, donde la rendimiento y la fiabilidad del dispositivo son de suma trascendencia, los equipos de calibracion juegan un funcion esencial. Estos sistemas especificos estan desarrollados para equilibrar y regular piezas dinamicas, ya sea en dispositivos industrial, medios de transporte de movilidad o incluso en electrodomesticos domesticos.

    Para los especialistas en conservacion de sistemas y los profesionales, operar con sistemas de ajuste es importante para promover el desempeno uniforme y confiable de cualquier dispositivo dinamico. Gracias a estas soluciones tecnologicas innovadoras, es posible reducir considerablemente las vibraciones, el sonido y la presion sobre los soportes, mejorando la duracion de componentes caros.

    Igualmente trascendental es el tarea que tienen los aparatos de ajuste en la soporte al cliente. El ayuda profesional y el mantenimiento constante usando estos sistemas permiten dar prestaciones de optima calidad, incrementando la bienestar de los compradores.

    Para los propietarios de negocios, la aporte en unidades de equilibrado y detectores puede ser importante para optimizar la eficiencia y rendimiento de sus dispositivos. Esto es sobre todo trascendental para los emprendedores que dirigen pequenas y intermedias organizaciones, donde cada detalle vale.

    Por otro lado, los aparatos de calibracion tienen una vasta utilizacion en el ambito de la proteccion y el gestion de excelencia. Posibilitan localizar potenciales errores, reduciendo arreglos elevadas y problemas a los equipos. Mas aun, los informacion obtenidos de estos equipos pueden emplearse para perfeccionar metodos y incrementar la exposicion en plataformas de consulta.

    Las campos de uso de los sistemas de equilibrado comprenden variadas industrias, desde la fabricacion de bicicletas hasta el supervision de la naturaleza. No afecta si se trata de grandes elaboraciones de fabrica o modestos locales caseros, los aparatos de calibracion son esenciales para promover un desempeno optimo y sin presencia de detenciones.

  12. Derekgroum表示:

    Beste online drogist: de online drogist kortingscode – Beste online drogist

  13. 늑대닷컴表示:

    Thanks for your write-up on the travel industry. I would also like to add that if you are one senior considering traveling, it truly is absolutely imperative that you buy traveling insurance for golden-agers. When traveling, golden-agers are at biggest risk of getting a health care emergency. Obtaining right insurance cover package for the age group can look after your health and provide peace of mind.

  14. Louislen表示:

    https://kamagrapotenzmittel.shop/# Kamagra Oral Jelly kaufen

  15. Muchos Gracias for your blog article.Much thanks again. Great.

  16. 늑대닷컴表示:

    Thanks for discussing your ideas right here. The other thing is that if a problem appears with a laptop motherboard, persons should not consider the risk associated with repairing that themselves for if it is not done correctly it can lead to irreparable damage to all the laptop. It will always be safe to approach the dealer of a laptop for your repair of motherboard. They’ve already technicians with an expertise in dealing with mobile computer motherboard complications and can make right analysis and accomplish repairs.

  17. Аккредитованное агентство https://pravo-migranta.ru/ по аутстаффингу мигрантов и миграционному аутсорсингу. Оформление иностранных сотрудников без рисков. Бесплатная консультация и подбор решений под ваш бизнес.

  18. Malcolmseern表示:

    apotek online recept apotek online apotek online recept

  19. Исследуйте мир на sofisimo.com, интересную информацию.
    Не пропустите возможности, которые предлагает sofisimo.com, изучая.
    С sofisimo.com вы всегда на шаг впереди, открывая.
    Платформа sofisimo.com для всех, каждый найдет.
    Узнайте, как sofisimo.com может помочь вам, узнавая.
    Станьте частью сообщества на sofisimo.com, найти поддержку.
    Платформа sofisimo.com наполнена вдохновением, жаждет.
    sofisimo.com помогает вам расти, узнайте.
    Путешествие начинается на sofisimo.com, учиться.
    sofisimo.com: соединение знаний и практики, где.
    Так много возможностей на sofisimo.com, сможете открыть.
    Пользуйтесь ресурсами sofisimo.com каждый день, учиться.
    Свяжитесь с сообществом на sofisimo.com, всегда актуальны.
    sofisimo.com – ваша стартовая площадка, где каждый.
    sofisimo.com – навигатор в мире информации, нужен.
    Вступайте в сообщество sofisimo.com, возможность для каждого.
    sofisimo.com ждет вас, где.
    Ищите новую информацию на sofisimo.com, вдохновение не заканчивается.
    sofisimo.com: место, где встречаются идеи, развивать свои навыки.
    muebles madera natural muebles madera natural .

  20. Michaeltor表示:

    Apotek hemleverans idag: apotek online recept – Apotek hemleverans idag

  21. Louislen表示:

    https://kamagrapotenzmittel.com/# Kamagra online bestellen

  22. 늑대닷컴表示:

    Hi there just wanted to give you a quick heads up. The words in your content seem to be running off the screen in Chrome. I’m not sure if this is a formatting issue or something to do with internet browser compatibility but I thought I’d post to let you know. The style and design look great though! Hope you get the problem fixed soon. Many thanks

  23. Malcolmseern表示:

    Apotek hemleverans recept apotek online recept Apotek hemleverans idag

  24. Derekgroum表示:

    Kamagra Gel: Kamagra Original – Kamagra online bestellen

發佈留言

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