如何从格式化的字符串中获取月中的某一天?

时间:2012-03-11 10:51:51

标签: java parsing datetime

当我通过解析Date创建String并访问该月的某一天时,我得到了错误的值。

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 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

你应该使用

int DPDDay = datearr.getDate();

getDay()返回一周中的一天

答案 2 :(得分: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();