2017-08-08 39 views
0

我想將字符串轉換爲日期,然後更改該日期格式以保存在日期對象中。日期將自動更改其格式。將字符串轉換爲日期,然後更改該日期格式

try { 
     String starttime = "10:00AM"; 
     SimpleDateFormat format = new SimpleDateFormat("hh:mma", Locale.ENGLISH); 
     Date startdat = format.parse(starttime); 
     Calendar calendar = Calendar.getInstance(); 

     Calendar startcalendar = Calendar.getInstance(); 
     startcalendar.setTime(startdat); 
     startcalendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); 

     java.text.DateFormat simpleformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSSZ", Locale.US); 

     String **time**=simpleformat.format(startcalendar.getTime()); 

     Log.e("taggg",String.valueOf(time)); 



    }catch (Exception e){ 
     e.printStackTrace(); 
     Log.e("error",e.getMessage()); 
    } 

我想時間變量在Date對象相同的格式保存。

+0

ü可以分享您的預期輸出 – Anil

+0

我的預期成果是2017年7月24日09:00 :00.000那樣 –

回答

0

檢查這個我已經更新

只要改變這個

java.text.DateFormat simpleformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US); 

所以更新

try { 
      String starttime = "10:00AM"; 
      SimpleDateFormat format = new SimpleDateFormat("hh:mma", Locale.ENGLISH); 
      Date startdat = format.parse(starttime); 
      Calendar calendar = Calendar.getInstance(); 

      Calendar startcalendar = Calendar.getInstance(); 
      startcalendar.setTime(startdat); 
      startcalendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); 

      java.text.DateFormat simpleformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US); 

      String time=simpleformat.format(startcalendar.getTime()); 

      Log.e("taggg",String.valueOf(time)); 



     }catch (Exception e){ 
      e.printStackTrace(); 
      Log.e("error",e.getMessage()); 
     } 
+0

當我使用parse()方法將日期格式轉換爲日期格式時,它的更改默認格式Tue Aug 08 10:00:00 GMT + 05:30 2017 –

+0

請清楚你的問題你得到了什麼,你期待什麼 – Anil

+0

2017-07-24 09:00:00.000預計在該格式,但在日期對象 –

相關問題