我刚开始使用Java(Android)并且遇到了日期格式问题。 我有一个小表单,您可以在其中输入项目名称并在日历上选择开始日期。获取Startdate和Projectname后输入数据库,然后将预定义的任务自动输入到数据库中。
我现在已经提出了下面的源代码,除了我得到错误的日期格式之外,一切正常。出于某种原因,我的格式在newDateStr中是正确的,但是当我再次将其解析为日期对象时,格式会发生变化并且不正确。我看不出自己的错误,任何人都可以帮忙吗?
我的理解是:
因为我需要再次使用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
我希望有人看到我的错误。非常感谢你提前!
答案 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框架倾向于内置自动执行此功能的工具。)