使用J2ME,netbeans 7.2,开发移动应用程序..
我已将Datefield值转换为String,现在想将其重新放回Datefield。为此,我需要将String转换回Datefield,我使用以下代码,但它没有发生。
long myFileTime = dateField.getDate().getTime(); // getting current/set date from the datefield into long
String date = String.valueOf(myFileTime); // converting it to a String to put it back into a different datefield
Date updatedate= stringToDate(date); // passing the string 'date' to the Method stringToDate() to convert it back to date.
dateField1.setDate(updatedate); // updating the date into the new datefield1
public Date stringToDate(String s)
{
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(s.substring(0, 2)));
c.set(Calendar.MONTH, Integer.parseInt(s.substring(3, 5)) - 1);
c.set(Calendar.YEAR, Integer.parseInt(s.substring(6, 10)));
return c.getTime();
}
答案 0 :(得分:1)
由于您已经提到周围有long myFileTime
,因此您应该可以使用:
Date updatedate=new Date(myFileTime);
转换回您的日期。如果只有String
可用,则应将功能修改为:
public Date stringToDate(String s){
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(s.substring(0, 2)));
c.set(Calendar.MONTH, Integer.parseInt(s.substring(2, 4))-1 );
c.set(Calendar.YEAR, Integer.parseInt(s.substring(4, 8)));
return c.getTime();
}
请注意更改的索引。
在Java SE中,您应该能够使用以下行,而不是分别设置每个字段:
c.setTimeInMillis(Long.parseLong(s));
在s
中,您的dateField.getDate().getTime()
等于myFileTime
,即1970年1月1日开始的秒数,基于您提供的代码。
只有当您的字符串具有以下格式时,stringToDate
才有效:ddMMyyyy
。另请注意,在这种情况下,您应该使用SimpleDateFormat进行解析,例如:
Date updatedate = new java.text.SimpleDateFormat("ddMMyyyy HH:mm:ss").parse(date);