Composing and comparing a date in Java
I used this to create a date and put it into a database:
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
I want to build a date with a similar format to the one above and compare it with currentDateTimeString
.
I have 3 integers. How do I do that (int year, int month, 开发者_运维知识库int day)?
UPDATE:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, month);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.DAY_OF_MONTH, day);
Date result = cal.getTime();
String currentDateTimeString2 = DateFormat.getDateInstance().format(result);
I do here something wrong..both arent equal: currentDateTimeString2==currentDateTimeString //false
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, date);
cal.set(Calendar.MONTH, month-1);//it starts from 0
cal.set(Calendar.YEAR, year);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date result = cal.getTime();
I do here something wrong..both arent equal: currentDateTimeString2==currentDateTimeString //false
String are object, it can't be compared with ==
use equals()
method
Dates are represented in milliseconds. new Date returns the current date, and by date it means year, month, day, hour, minute, second, millisecond.
Comparison can be made via Date.isAfter.
Don't use Strings to compare Dates. Don't use == to compare Objects.
精彩评论