日期:2014-05-20  浏览次数:20747 次

高分请教java 中,较难的时间问题
java.util.Date   data=   new   java.util.Date();

有个字符窜
String   strDate= "20070115,184021399, "//YYYYMMDD、hhmmss000
请问
1.如何转化为一个日期相关的类型(如Data,Calendar)?
2.如何判断前一天的日期?


------解决方案--------------------
DateFormat df = new SimpleDateFormat( "yyyyMMdd,HHmmssSSS ");
String dateStr = "20070115,184021399 ";//YYYYMMDD、hhmmss000
Calendar c = Calendar.getInstance();
c.setTime(df.parse(dateStr));
c.add(Calendar.DAY_OF_MONTH, -1);
System.out.println(df.format(c.getTime()));
------解决方案--------------------
给楼主一个例子吧:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateChange {

private final static String DATE_FORMAT = "yyyy-MM-dd ";

/**
* @param args
*/
public static void main(String[] args) {

Date day1=DateChange.getFormatDate( "20070115,184021399 ", "yyyymmdd,hhmmssSSS ");
System.out.println(day1);

Calendar c = Calendar.getInstance();
c.setTime(day1);

c.add(Calendar.DATE,-1);
System.out.println(c.getTime());
}


/**
* 根据格式得到格式化后的日期
* @param currDate 要格式化的日期
* @param format 日期格式,如yyyy-MM-dd
* @see java.text.SimpleDateFormat#parse(java.lang.String)
* @return Date 返回格式化后的日期,格式由参数 <code> format </code> 定义,如yyyy-MM-dd,如2006-02-15
*/
public static Date getFormatDate(String currDate, String format) {
SimpleDateFormat dtFormatdB = null;
try {
dtFormatdB = new SimpleDateFormat(format);
return dtFormatdB.parse(currDate);
} catch (Exception e) {
dtFormatdB = new SimpleDateFormat(DATE_FORMAT);
try {
return dtFormatdB.parse(currDate);
} catch (Exception ex){}
}
return null;
}
}
------解决方案--------------------
DateFormat df = new SimpleDateFormat( "yyyyMMdd,HHmmssSSS ");
String dateStr = "20070115,184021399 ";//YYYYMMDD、hhmmss000
Calendar c = Calendar.getInstance();
c.setTime(df.parse(dateStr));
c.add(Calendar.DAY_OF_MONTH, -1);
System.out.println(df.format(c.getTime()));
------解决方案--------------------
DateFormat df = new SimpleDateFormat( "yyyyMMdd,HHmmssSSS ");
String dateStr = "20070115,184021399 ";//YYYYMMDD、hhmmss000
Calendar c = Calendar.getInstance();
c.setTime(df.parse(dateStr));
c.add(Calendar.DAY_OF_MONTH, -1);
------解决方案--------------------
DateFormat df = new SimpleDateFormat( "yyyyMMdd,HHmmssSSS ");
String dateStr = "20070115,184021399 ";//YYYYMMDD、hhmmss000
Calendar c = Calendar.getInstance();
c.setTime(df.parse(dateStr));
c.add(Calendar.DAY_OF_MONTH, -1);
System.out.println(df.format(c.getTime()));
------解决方案--------------------
DateFormat
------解决方案--------------------
try catch