getStartDate方法返回util.Date类型对象。我需要一种方法将“今天”(String类型的Date对象)转换为util.Date对象,格式为MM / dd / yyyy 如果我将“今天”字符串日期格式化为Date对象,我将获得长日期格式。
public Date getStartDate() {
try {
System.out.println("startDate" + startDate); // prints Fri Jan 02 00:00:00 EST 1998
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String today = formatter.format(startDate);
System.out.println("today" + today); // prints 02/01/1998 (I need to return Date object in this format)
DateFormat formatter2 = new SimpleDateFormat("MM/dd/yyyy");
Date reformatedDate = formatter2.parse(today);
System.out.println("reformatedDate" + reformatedDate); // Fri Jan 02 00:00:00 EST 1998
return reformatedDate;
} catch (Exception e) {
}
return null;
}
答案 0 :(得分:0)
可以做这样的事情来解析日期:
Format formatter = new SimpleDateFormat("MM/dd/yyyy");
String dateString = "02/01/1998";
Date date = null;
try {
date = (Date)((DateFormat) formatter).parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
String.format("%02d", month);
String.format("%02d", day);
String yourDate = month + "/" + day + "/" + year;