我需要比较两个字符串日期和SimpleDateformat,如EE,MMM dd yyyy 但是当我比较它时,它只会验证第一个值" EE"只有其他月份,日期和年份不验证是否有人知道此问题解决方案请帮我解决并提前感谢所有
答案 0 :(得分:1)
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy"/*or whatever your format is*/, Locale.US);
try {
Date actualDate = format.parse(actualDate);
Date dateToCompare = format.parse(dateToCompare);
if (actualDate.after(dateToCompare) || actualDate.before(dateToCompare)) {
// Toast.makeText(context,""+actualDate.toString(),Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
将其与日期格式进行比较,然后使用字符串结果。
答案 1 :(得分:0)
试试这个:
public static void main( String[] args )
{
try{
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy");
Date date1 = sdf.parse("date1 example");
Date date2 = sdf.parse("date2 example");
System.out.println(sdf.format(date1));
System.out.println(sdf.format(date2));
if(date1.compareTo(date2)>0){
System.out.println("Date1 is > Date2");
}else if(date1.compareTo(date2)<0){
System.out.println("Date1 is <Date2");
}else if(date1.compareTo(date2)==0){
System.out.println("Date1 is = to Date2");
}else{
System.out.println("!!!");
}
}catch(ParseException ex){
ex.printStackTrace();
}
}
<强>更新强>
如果您想使用Calendar
:
public static void main( String[] args )
{
try{
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy");
Date date1 = sdf.parse("date1 example");
Date date2 = sdf.parse("date2 example");
System.out.println(sdf.format(date1));
System.out.println(sdf.format(date2));
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
if(cal1.after(cal2)){
System.out.println("Date1 is > Date2");
}
if(cal1.before(cal2)){
System.out.println("Date1 is < Date2");
}
if(cal1.equals(cal2)){
System.out.println("Date1 is = Date2");
}
}catch(ParseException ex){
ex.printStackTrace();
}
}
如果您想在日期中添加日期,请执行以下操作:
String date = "your date"; // your date
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(date));
c.add(Calendar.DATE, 3); // 3 days to add
date= sdf.format(c.getTime()); // put the new date in date variable
希望有所帮助
答案 2 :(得分:0)
try{
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy");
Date date1 = sdf.parse("Mon Oct 17 2016");
Date date2 = sdf.parse("Tue Oct 18 2016");
System.out.println(sdf.format(date1));
System.out.println(sdf.format(date2));
if(date1.compareTo(date2)>0){
System.out.println("Date1 is after Date2");
}else if(date1.compareTo(date2)<0){
System.out.println("Date1 is before Date2");
}else if(date1.compareTo(date2)==0){
System.out.println("Date1 is equal to Date2");
}else{
System.out.println("How to get here?");
}
}catch(ParseException ex){
ex.printStackTrace();
}