Code liên quan đến xử lý Date
Java Date API
java.util.
Class Date
java.lang.Object
extended by java.util.Date
All Implemented Interfaces:
Cloneable, Comparable, Serializable
Direct Known Subclasses:
Date, Time, Timestamp
public class Date extends Object implements Serializable, Cloneable, Comparable
Lớp Date biểu diễn 1 khoảnh khác thời gian chỉ định với độ chính xác đến milisecond.
Sau đây là 1 số phương thức xử lý ngày cơ bản:
1> Thêm Day/Month/Year vào 1 Date
|
public static void addToDate(){ System.out.println(“1. Add to a Date Operation\n”); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); // Gets a calendar using the default time zone and locale. Calendar c1 = Calendar.getInstance(); Date d1 = new Date(); System.out.println(“Todays date in Calendar Format : ”+c1); System.out.println(“c1.getTime() : ”+c1.getTime()); System.out.println(“c1.get(Calendar.YEAR): ” + c1.get(Calendar.YEAR));
System.out.println(“Todays date in Date Format : ”+d1); c1.set(2008,02 ,20); //(year,month,date) System.out.println(“c1.set(2008,02 ,20) : ”+c1.getTime()); c1.add(Calendar.DATE,20); System.out.println(“Date + 20 days is : ” + sdf.format(c1.getTime())); System.out.println(); System.out.println(“——————————————————-”); } |
2> Khoảng thời gian giữa 2 cột mốt ngày tháng
Đôi lúc chúng ta muốn trừ 2 ngày để lấy khoảng thời gian giữa 2 ngày, hàm sau đây demo việc đó
/*Phương thức roll() dùng để hiệu các giá trị giữa các đối tượng Calendar, bạn phải chỉ định trường của đối tượng Calendar nào ảnh hưởng bởi thao tác này.
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE). Ghi chú: Để hiệu 2 ngày bạn chỉ đơn giản chỉ định false trong tham số của phương thức roll() Theo JDK: /** * Adds or subtracts (up/down) a single unit of time on the given time * field without changing larger fields. For example, to roll the current * date up by one day, you can achieve it by calling: * <p>roll(Calendar.DATE, true). * When rolling on the year or Calendar.YEAR field, it will roll the year * value in the range between 1 and the value returned by calling * <code>getMaximum(Calendar.YEAR)</code>. * When rolling on the month or Calendar.MONTH field, other fields like * date might conflict and, need to be changed. For instance, * rolling the month on the date 01/31/96 will result in 02/29/96. * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will * roll the hour value in the range between 0 and 23, which is zero-based. * * @param field the time field. * @param up indicates if the value of the specified time field is to be * rolled up or rolled down. Use true if rolling up, false otherwise. * @see Calendar#add(int,int) * @see Calendar#set(int,int) */ */
public static void subToDate(){ System.out.println(“2. Subtract to a date Operation\n”);
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); Calendar c1 = Calendar.getInstance(); c1.set(2008, 02 , 20); System.out.println(“Date is : ” + sdf.format(c1.getTime()));
// roll down, substract 1 month c1.roll(Calendar.MONTH, false); System.out.println(“Date roll down 1 month : ” + sdf.format(c1.getTime())); c1.set(2008, 02 , 20); System.out.println(“Date is : ” + sdf.format(c1.getTime())); c1.add(Calendar.MONTH, -1); // substract 1 month System.out.println(“Date minus 1 month : ” + sdf.format(c1.getTime())); System.out.println(); System.out.println(“——————————————————-”); } |
3>Đếm số ngày giữa 2 cột mốt thời gian:
|
public static void daysBetween2Dates(){ System.out.println(“3. No of Days between 2 dates\n”); Calendar c1 = Calendar.getInstance(); //new GregorianCalendar(); Calendar c2 = Calendar.getInstance(); //new GregorianCalendar(); c1.set2008, 02, 20); c2.set(2008, 02 , 22); System.out.println(“Days Between ”+c1.getTime()+“ and ”+ c2.getTime()+“ is”); System.out.println((c2.getTime().getTime() - c1.getTime().getTime())/(24*3600*1000)); System.out.println(); System.out.println(“——————————————————-”); } |
4>Đếm số ngày trong tháng
|
public static void daysInMonth() { System.out.println(“4. No of Days in a month for a given date\n”); Calendar c1 = Calendar.getInstance(); //new GregorianCalendar(); c1.set(2008, 6 , 20); int year = c1.get(Calendar.YEAR); int month = c1.get(Calendar.MONTH); // int days = c1.get(Calendar.DATE); int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31}; daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0; System.out.println(“Days in ”+month+“th month for year ”+year+“ is ” + daysInMonths[c1.get(Calendar.MONTH)]); System.out.println(); System.out.println(“——————————————————-”); } |
5>Xác định 1 giá trị có phải 1 ngày hay không
|
public static void validateAGivenDate() { System.out.println(“5. Validate a given date\n”); String dt = “20011223″; String invalidDt = “20031315″; String dateformat = “yyyyMMdd”; Date dt1=null , dt2=null; try { SimpleDateFormat sdf = new SimpleDateFormat(dateformat); sdf.setLenient(false); dt1 = sdf.parse(dt); dt2 = sdf.parse(invalidDt); System.out.println(“Date is ok = ” + dt1 + “(” + dt + “)”); } catch (ParseException e) { System.out.println(e.getMessage()); } catch (IllegalArgumentException e) { System.out.println(“Invalid date”); } System.out.println(); System.out.println(“——————————————————-”); } |
6>So sánh 2 ngày
|
public static void compare2Dates(){ System.out.println(“6. Comparision of 2 dates\n”); SimpleDateFormat fm = new SimpleDateFormat(“dd-MM-yyyy”); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance();
c1.set(2000, 02, 15); c2.set(2001, 02, 15);
System.out.print(fm.format(c1.getTime())+“ is ”); if(c1.before(c2)){ System.out.println(“less than ”+fm.format(c2.getTime())); }else if(c1.after(c2)){ System.out.println(“greater than ”+fm.format(c2.getTime())); }else if(c1.equals(c2)){ System.out.println(“is equal to ”+fm.format(c2.getTime())); } System.out.println(); System.out.println(“——————————————————-”); } |
7>Lấy giá trị ngày(day) trong 1 kiểu Date
|
public static void getDayofTheDate() { System.out.println(“7. Get the day for a given date\n”); Date d1 = new Date(); String day = null; DateFormat f = new SimpleDateFormat(“EEEE”); try { day = f.format(d1); } catch(Exception e) { e.printStackTrace(); } System.out.println(“The day for ”+d1+“ is ”+day); System.out.println(); System.out.println(“——————————————————-”); } |
8>Kiểm tra 1 năm có phải năm nhuần không
|
public static boolean isLeapYear(int year){ if((year%100 != 0) || (year%400 == 0)){ return true; } return false; } |
8>Hàm main chạy thử chương trình
|
public static void main(String args[]){ addToDate(); //Add day, month or year to a date field. subToDate(); //Subtract day, month or year to a date field. daysBetween2Dates(); //The ”right” way would be to compute the julian day number of both dates and then do the substraction. daysInMonth(); //Find the number of days in a month for a given date validateAGivenDate(); //Check whether the date format is proper // Convert String to Date using parse function compare2Dates(); //Compare 2 dates getDayofTheDate(); } |
Kết quả:
| 1. Add to a Date OperationTodays date in Calendar Format : java.util.GregorianCalendar[time=1241581644981,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Bangkok",offset=25200000,dstSavings=0,useDaylight=false,transitions=3,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2009,MONTH=4,WEEK_OF_YEAR=19,WEEK_OF_MONTH=2,DAY_OF_MONTH=6,DAY_OF_YEAR=126,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=10,HOUR_OF_DAY=10,MINUTE=47,SECOND=24,MILLISECOND=981,ZONE_OFFSET=25200000,DST_OFFSET=0]
c1.getTime() : Wed May 06 10:47:24 ICT 2009 c1.get(Calendar.YEAR): 2009 Todays date in Date Format : Wed May 06 10:47:24 ICT 2009 c1.set(2008,02 ,20) : Thu Mar 20 10:47:24 ICT 2008 Date + 20 days is : 09-04-2008 ——————————————————- 2. Subtract to a date Operation Date is : 20-03-2008 Date roll down 1 month : 20-02-2008 Date is : 20-03-2008 Date minus 1 month : 20-02-2008 ——————————————————- 3. No of Days between 2 dates Days Between Thu Mar 20 10:47:24 ICT 2008 and Sat Mar 22 10:47:24 ICT 2008 is 2 ——————————————————- 4. No of Days in a month for a given date Days in 6th month for year 2008 is 31 ——————————————————- 5. Validate a given date Unparseable date: “20031315″ ——————————————————- 6. Comparision of 2 dates 15-03-2000 is less than 15-03-2001 ——————————————————- 7. Get the day for a given date The day for Wed May 06 10:47:24 ICT 2009 is Thứ tư ——————————————————- |
Tham khảo trang: http://www.javabeginner.com/learn-java/introduction-to-java-programming!
Chúc các bạn thành công!
Tùng said
hàm tính khoảng cách giữa 2 ngày của bạn chỉ tính dc trong cùng 1 tháng.
nếu 2 ngày cần tính nằm ở 2 tháng khác nhau thì sẽ tính ra kết quả sai.
please fix
nguyen viet tram said
Thầy ơi, giúp em vấn đề này với:
Em định đạng ngày tháng là : “dd/mm/yyyy”
De bai nhu sau: khi nhập vào 1 ngày tháng năm nào đó(28/04/2010):
- Nếu thời gian nhập >12h trưa thì sẽ in ra
-> bạn nộp HS sau 12h trua, nen HS của bạn sẽ xử lý trong ngày 29/04/2010 (tăng thêm 1 ngày)
- Nếu thời gian nhập bạn nộp HS truoc 12h trua, nen HS của bạn sẽ xử lý trong ngày 28/04/2010.
———
Thanks thầy
Võ Văn Hải said
Tham khảo bài viết xử lý ngày trên blog này nhé!
Dark wolf said
Thầy xem lại phần đếm số ngày giữa 2 mốc thời gian ,em thấy có 1 sự sai lệch ! chưa chính xác với những mốc thời gian khác tháng !
trương quang trầm said
thầy ơi thầy có thể cho em cái code để lấy giờ hệ thống ko thầy.em làm đề tài mà ko biết.thầy giup em với,em cảm ơn nhiều ạh.
Võ Văn Hải said
Em dùng java.util.Date systemTime=new java.util.Date();
là em có ngya2 giờ hệ thống rồi đó.
trương quang trầm said
thầy ơi sao em làm mà ko đc thầy ơi,thầy giúp em đi sắp nộp đề tài rồi mà em chưa làm đc
đây la bài em lầm nè thây chinh sửa giúp em với http://www.mediafire.com/?fo3pmo3fl9fomqn
chèn giò hệ thống vào textarea do thầy
cảm ơn thầy nhiều ah
Lê Xuân Nguyên said
Rất hữu ích