Using J2ME, netbeans 7.2, Developing a mobile app..
I have converted the Datefield value to a String and Now want to put it back to a Datefield. To do this I need to convert the String back to Datefield, I am using the following code but its not happening.
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();
}
Since you have mentioned that you have the
long myFileTime
around, you should be able to use:To convert back to your date. If only your
String
is available, you should modify your function to this:Note the changed indexes.
In Java SE, you should be able to use the following line, instead of setting each fields separately:
Since in
s
you have thedateField.getDate().getTime()
that is equal tomyFileTime
, the number of seconds starting with January 1, 1970, based on your provided code.Your
stringToDate
should work only if your string will have the following format:ddMMyyyy
. Also note that in this case you should use a SimpleDateFormat to parse, something like: