Convert string to Date in java
我试图在Android应用程序中将一个字符串解析为日期字段,但我似乎无法得到正确的结果。这是我试图转换为日期"03/26/2012 11:49:00 am"的字符串。我使用的功能是:
1 2 3 4 5 6 7 8 9 10 11 | private Date ConvertToDate(String dateString){ SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa"); Date convertedDate = new Date(); try { convertedDate = dateFormat.parse(dateString); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return convertedDate; } |
但结果我还是得到了
我猜你显示数据的方式是错误的,因为对我来说:
1 2 3 4 5 6 7 8 9 10 | String dateString ="03/26/2012 11:49:00 AM"; SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa"); Date convertedDate = new Date(); try { convertedDate = dateFormat.parse(dateString); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(convertedDate); |
印刷品:
1 | Mon Mar 26 11:49:00 EEST 2012 |
当我在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | String dateString ="15 May 2013 17:38:34 +0300"; System.out.println(dateString); SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.US); DateFormat targetFormat = new SimpleDateFormat("dd MMM yyyy HH:mm", Locale.getDefault()); String formattedDate = null; Date convertedDate = new Date(); try { convertedDate = dateFormat.parse(dateString); System.out.println(dateString); formattedDate = targetFormat.format(convertedDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(convertedDate); |
1 2 3 4 5 6 | String str_date="13-09-2011"; DateFormat formatter ; Date date ; formatter = new SimpleDateFormat("dd-MM-yyyy"); date = (Date)formatter.parse(str_date); System.out.println("Today is" +date.getTime()); |
试试这个
此代码将帮助您获得2月17日20:49这样的结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | String myTimestamp="2014/02/17 20:49"; SimpleDateFormat form = new SimpleDateFormat("yyyy/MM/dd HH:mm"); Date date = null; Date time = null; try { date = form.parse(myTimestamp); time = new Date(myTimestamp); SimpleDateFormat postFormater = new SimpleDateFormat("MMM dd"); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); String newDateStr = postFormater.format(date).toUpperCase(); String newTimeStr = sdf.format(time); System.out.println("Date :"+newDateStr); System.out.println("Time :"+newTimeStr); } catch (Exception e) { e.printStackTrace(); } |
结果:
日期:2月17日
时间:20:49
1 2 3 4 5 6 7 8 9 10 11 12 | SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); String dateInString ="07/06/2013"; try { Date date = formatter.parse(dateInString); System.out.println(date); System.out.println(formatter.format(date)); } catch (ParseException e) { e.printStackTrace(); } |
输出:
1 2 | 2014/08/06 16:06:54 2014/08/06 16:06:54 |
1 2 3 4 5 | GregorianCalendar date; CharSequence dateForMart = android.text.format.DateFormat.format("yyyy-MM-dd", date); Toast.makeText(LogmeanActivity.this,dateForMart,Toast.LENGTH_LONG).show(); |