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 } }
Kamagra kaufen: Kamagra online bestellen – Kamagra Original
https://apotheekmax.com/# ApotheekMax
http://apotekonlinerecept.com/# Apoteket online
Brace yourself for the highs and lows, as the Spot Market is famous for its rapid price jumps.
apotek online recept: Apoteket online – Apoteket online
https://kamagrapotenzmittel.com/# kamagra
Thanks a lot for the blog. Really Great.
Online apotheek Nederland met recept: de online drogist kortingscode – Beste online drogist
kamagra Kamagra Original Kamagra Original
Online apotheek Nederland met recept: Online apotheek Nederland met recept – Beste online drogist
Betrouwbare online apotheek zonder recept: Apotheek Max – Online apotheek Nederland met recept
https://apotekonlinerecept.shop/# Apoteket online
Online apotheek Nederland met recept Online apotheek Nederland zonder recept Apotheek Max
Recomendo o jogo a todos Fortune Tiger
http://apotheekmax.com/# Beste online drogist
http://kamagrapotenzmittel.com/# Kamagra online bestellen
Apoteket online: Apotek hemleverans recept – Apotek hemleverans recept
vibración de motor
Equipos de balanceo: esencial para el rendimiento suave y efectivo de las máquinas.
En el entorno de la avances contemporánea, donde la eficiencia y la seguridad del dispositivo son de gran significancia, los sistemas de calibración desempeñan un función vital. Estos sistemas dedicados están concebidos para calibrar y asegurar componentes giratorias, ya sea en equipamiento manufacturera, transportes de desplazamiento o incluso en dispositivos de uso diario.
Para los profesionales en conservación de aparatos y los ingenieros, operar con sistemas de ajuste es fundamental para proteger el rendimiento suave y seguro de cualquier dispositivo móvil. Gracias a estas alternativas avanzadas innovadoras, es posible disminuir sustancialmente las vibraciones, el estruendo y la esfuerzo sobre los sujeciones, mejorando la duración de elementos importantes.
También importante es el rol que cumplen los sistemas de ajuste en la atención al usuario. El apoyo experto y el soporte constante usando estos dispositivos habilitan brindar asistencias de óptima calidad, elevando la contento de los compradores.
Para los propietarios de proyectos, la inversión en sistemas de calibración y dispositivos puede ser fundamental para optimizar la efectividad y rendimiento de sus sistemas. Esto es principalmente relevante para los empresarios que manejan modestas y modestas organizaciones, donde cada elemento vale.
También, los aparatos de ajuste tienen una extensa implementación en el ámbito de la protección y el supervisión de estándar. Permiten encontrar probables defectos, reduciendo intervenciones elevadas y averías a los aparatos. Incluso, los datos recopilados de estos sistemas pueden utilizarse para optimizar procedimientos y mejorar la exposición en motores de investigación.
Las zonas de aplicación de los equipos de ajuste abarcan diversas áreas, desde la producción de ciclos hasta el supervisión de la naturaleza. No interesa si se habla de importantes producciones manufactureras o reducidos establecimientos domésticos, los sistemas de calibración son fundamentales para asegurar un desempeño productivo y sin presencia de fallos.
Apoteket online: apotek online recept – apotek online
https://apotekonlinerecept.com/# apotek online
Use 1XBET promo code: 1XTAX200 for VIP bonus up to €1950 + 150 free spins on casino and 100% up to €130 to bet on sports. Register on the 1xbet platform and get a chance to earn even more Rupees using bonus offers and special bonus code from 1xbet. Make sports bets, virtual sports or play at the casino. Join 1Xbet and claim your welcome bonus using the latest 1Xbet promo codes. Check below list of 1Xbet signup bonuses, promotions and product reviews for sportsbook, casino, poker and games sections. To claim any of the 1Xbet welcome bonuses listed in above table we recommend using the 1Xbet bonus code at registration of your account. New customers will get a €130 exclusive bonus (International users) when registering using the 1Xbet promo code listed above. 1Xbet Sportsbook section is the main place where users hang out, with over 1000 sporting events to bet each day. There are multiple choices to go for, and the betting markets, for example for soccer matches, can even pass 300 in number, and that is available for both pre-match and live betting, which is impressive and puts it right next to the big names in the industry.
The 1xBet promo code: 1XTAX200. Enter code for registration and receive a 100% bonus up to €100 for free sports bets. This offer is valid for new players. Enter our bonus code for 1XBET in the registration form and claim exclusive bonuses for casino and sports betting.
1xbet promo code free bet
Apoteket online apotek pa nett Apotek hemleverans idag
https://apotheekmax.com/# Online apotheek Nederland met recept
apotek online: apotek online – apotek pa nett
Apotek hemleverans recept apotek pa nett Apotek hemleverans idag
Online apotheek Nederland met recept: Online apotheek Nederland met recept – de online drogist kortingscode
http://apotheekmax.com/# Beste online drogist
https://kamagrapotenzmittel.shop/# Kamagra Oral Jelly
https://apotheekmax.com/# Online apotheek Nederland zonder recept
Online apotheek Nederland met recept: Beste online drogist – Online apotheek Nederland zonder recept