0

I have a String in the Format dd.MM.yy HH:mm e.g. 12.04.14 07:00. I convert that String into a Date object with the lines:

SimpleDateFormat sdfToDate = new SimpleDateFormat("dd.MM.yy HH:mm");
Date date_new = sdfToDate.parse(date);

But then the Date is in the following Format:

Apr 12, 2014 7:00:00 AM

I need to display 24h Time. How I can do that?

user3452015
  • 33
  • 11

4 Answers4

2

try this

String dateStr = "Apr 12, 2014 7:00:00 AM";
DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
Date date = null;
try
{
    date = readFormat.parse( dateStr );
}
catch ( ParseException e )
{
        e.printStackTrace();
}
if( date != null )
{
    String formattedDate = writeFormat.format( date );
}
0

Do it this way:

Date date = new SimpleDateFormat("dd.MM.yy HH:mm").parse("12.04.14 07:00");
String formated = new SimpleDateFormat("dd.MM.yy HH:mm:ss").format(date);
System.out.println(formated);

OUTPUT:

12.04.14 07:00:00
Harmlezz
  • 7,972
  • 27
  • 35
  • I need a Date object not a String. – user3452015 Apr 11 '14 at 10:56
  • The Date object you already get in the first line. And if you call the `toString()` method, do not wonder but read the Javadoc, which states: _Converts this `Date` object to a `String` of the form: dow mon dd hh:mm:ss zzz yyyy_ – Harmlezz Apr 11 '14 at 11:00
  • Yes. But I don't call the method toString(). I want to use this date object in a JSON Array, but I need 24h time. – user3452015 Apr 11 '14 at 11:05
  • Could you add the code where you convert the date to JSON to your question? How should one know? The question is not even tagged with JSON. – Harmlezz Apr 11 '14 at 11:10
  • You can't know. But I thought it is not necessary. When I call System.out.println(date) it should be the same. – user3452015 Apr 11 '14 at 11:37
0
String formattedDate=null;
String dateStr = "Jul 27, 2011 8:35:29 PM";
DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
Date date = null;
try
{
    date = readFormat.parse( dateStr );

}
catch ( ParseException e )
{
        e.printStackTrace();
}
if( date != null )
{
    formattedDate = writeFormat.format( date );

}
try
{
    Date format=writeFormat.parse(formattedDate);

}
catch ( ParseException e )
{
        e.printStackTrace();
}

If you want as a date object again convert using format method. final date object

Date format=writeFormat.parse(formattedDate);

Bruce
  • 8,609
  • 8
  • 54
  • 83
0

use this code that will give you output in 24 hour format

Date d = new Date();
String dd = new SimpleDateFormat("yyyy-MM-dd k:mm:ss").format(d);

output will be

2014-04-11 18:20:55

Smit Shilu
  • 345
  • 3
  • 17