用Java格式化和解析日期和字符串

时间:2012-11-26 16:40:23

标签: java android

我刚开始使用Java(Android)并且遇到了日期格式问题。 我有一个小表单,您可以在其中输入项目名称并在日历上选择开始日期。获取Startdate和Projectname后输入数据库,然后将预定义的任务自动输入到数据库中。

  • 任务1截止日期为Startdate,
  • 任务2是Startdate plus x days = DueDate2,
  • 任务3是DueDate2加x天= DueDate3

我现在已经提出了下面的源代码,除了我得到错误的日期格式之外,一切正常。出于某种原因,我的格式在newDateStr中是正确的,但是当我再次将其解析为日期对象时,格式会发生变化并且不正确。我看不出自己的错误,任何人都可以帮忙吗?

我的理解是:

  1. 设置输入日期的日期格式(curFormat)
  2. 设置目标日期格式(postFormater)
  3. 此时解析你的日期字符串,将其变成日期对象(使用curFormat)
  4. 格式化此日期以获取目标日期格式(使用postFormater),现在再次为字符串
  5. 再次解析这个以使其恢复为日历所需的日期
  6. 使用日历实例,setTime(此处为格式化日期)并添加x天
  7. 格式化日期以获取目标日期格式(使用postFormater),现在再次为字符串
  8. 因为我需要再次使用Date对象,我必须再次解析它。

    // The format of your input date string
    SimpleDateFormat curFormater = new SimpleDateFormat("MM/dd/yyyy"); 
    
    // The format of your target date string
    SimpleDateFormat postFormater = new SimpleDateFormat("dd-MM-yyyy"); 
    
    // The calendar instance which adds a locale to the date
    Calendar cal = Calendar.getInstance();
    
    // Parse the string (pro.getStart()) to return a Date object 
    Date dateObj = curFormater.parse(pro.getStart()); 
    
    // Format the Date dd-MM-yyyy
    String newDateStr = postFormater.format(dateObj);
    
    // Parse the string to return a Date object
    Date Startdate = postFormater.parse(newDateStr);
    
    while (cur.isAfterLast() == false) 
    {
        Integer delayTime = cur.getInt(cur.getColumnIndex("DelayTime"));    
    if (flag == false)
    {
        dateInString = Startdate;
        flag = true;
    }else{
        cal.setTime(dateInString);
        // add the extra days
        cal.add(Calendar.DAY_OF_MONTH, delayTime);
        // Format the Date dd-MM-yyyy
        newDateStr =  postFormater.format(cal.getTime()); 
        // Parse the string to return a Date object
        dateInString =  postFormater.parse(newDateStr);
    
    
    Log.i("newDateStr Format",newDateStr.toString()); // 29-11-2012
    Log.i("dateInString parse",dateInString.toString()); // Thu Nov 29 00:00:00 GMT 2012
    
  9. 我希望有人看到我的错误。非常感谢你提前!

2 个答案:

答案 0 :(得分:0)

每次循环时都不要将Calendar转换回字符串。保留一个,只是累积延迟......

SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();

// Set the date once
cal.setTime(fmt.parse(pro.getStart()));

while(!cur.isAfterLast()) {
    // Accumulate additional days
    Integer delayTime = cur.getInt(cur.getColumnIndex("DelayTime"));
    cal.add(Calendar.DAY_OF_MONTH, delayTime);
}

String endDate = fmt.format(cal.getTime());

答案 1 :(得分:0)

java.util.Date对象中没有任何格式或用于解析它的格式的内存。它的toString方法的输出,以及从dateInString.toString()输出的结果将始终采用您所看到的默认JDK格式:Thu Nov 29 00:00:00 GMT 2012

每当要显示格式化程序时,都必须使用格式化程序将其转换为格式化字符串。你不能这样说“格式化日期对象”。 (UI框架倾向于内置自动执行此功能的工具。)