1

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();
}
4

1 に答える 1

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));

sdateField.getDate().getTime()等しいので、myFileTime提供されたコードに基づいて、1970年1月1日から始まる秒数。

文字stringToDate列の形式が次の場合にのみ機能するはずですddMMyyyy。また、この場合、次のようにSimpleDateFormatを使用して解析する必要があることに注意してください。

Date updatedate = new java.text.SimpleDateFormat("ddMMyyyy HH:mm:ss").parse(date);
于 2012-11-22T08:42:05.380 に答える