将字符串转换为日期,然后更改该日期格式

问题描述:

我想将字符串转换为日期,然后更改该日期格式以保存在日期对象中。日期将自动更改其格式。将字符串转换为日期,然后更改该日期格式

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那样 –

检查这个我已经更新

只要改变这个

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预计在该格式,但在日期对象 –