2012-03-11 39 views
-1

当我通过解析String创建Date并访问月份的日期时,我得到错误的值。如何从格式化的字符串中获取月份的日期?

Date datearr = null; 
DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy"); 
String dataa = "17-03-2012"; 
try { 
    datearr = df1.parse(dataa); 
} catch (ParseException e) { 
    Toast.makeText(this, "err", 1000).show(); 
} 

int DPDMonth = datearr.getMonth() + 1; 
int DPDDay = datearr.getDay(); 
int DPDYear = datearr.getYear() + 1900; 

System.out.println(Integer.toString(DPDDay)+"-"+Integer.toString(DPDMonth)+"-"+Integer.toString(DPDYear)); 

为什么我得到0代替17

03-11 10:24:44.286: I/System.out(2978): 0-3-2012 
+3

阅读您使用的方法的javadoc,注意它们的弃用警告,并替换为文档建议的代码。而且,想想执行代码'datearr.getMonth()'时,如果您有ParseException会发生什么。 – 2012-03-11 10:55:50

+2

并请使用与变量命名有关的Java约定......它非常讨厌尝试读取代码并将变量突出显示为一个类。 – Marcelo 2012-03-11 11:06:44

+0

对不起,我的第一篇文章在这里。 – 2012-03-11 11:14:38

回答

1

回到这里一天的一个片段中不使用过时的方法了,修复的命名问题,并简化了输出。

Date datearr = null; 
    DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy"); 
    String dataa = "17-03-2012"; 
    try { 
     datearr = df1.parse(dataa); 
    } catch (ParseException e) { 
     Toast.makeText(this, "err", 1000).show(); 
     return; // do not continue in case of a parse problem!! 
    } 

    // "convert" the Date instance to a Calendar 
    Calendar cal = Calendar.getInstance(); 
    cal.setTime(datearr); 

    // use the Calendar the get the fields 
    int dPDMonth = cal.get(Calendar.MONTH)+1; 
    int dPDDay = cal.get(Calendar.DAY_OF_MONTH); 
    int dPDYear = cal.get(Calendar.YEAR); 

    // simplified output - no need to create strings 
    System.out.println(dPDDay+"-"+dPDMonth+"-"+dPDYear); 
0

您应该使用

int DPDDay = datearr.getDate(); 

getDay()在本周

+0

zoon nooz,thx!对不起,大家都是因为我的粗心大意 – 2012-03-11 11:19:15

0

这种工作在使用第三方库时更容易,Joda-Time 2.3。

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so. 
// import org.joda.time.*; 
// import org.joda.time.format.*; 

String dateString = "17-03-2012"; 

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy"); 
DateTime dateTime = formatter.parseDateTime(dateString).withTimeAtStartOfDay(); 

int dayOfMonth = dateTime.getDayOfMonth(); 
相关问题