0

Can someone tell me how to convert this string 2012-01-01T08:44:36+01:00 to 2012-01-01 08:44:36 in Java?

Thanks

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
Veljko
  • 1,708
  • 12
  • 40
  • 80
  • 3
    See: http://stackoverflow.com/questions/2201925 – Tomasz Nurkiewicz Feb 06 '12 at 08:40
  • 1
    possible duplicate of [Converting ISO8601-compliant String to java.util.Date](http://stackoverflow.com/questions/2201925/converting-iso8601-compliant-string-to-java-util-date) – Jacob Feb 07 '12 at 00:29

4 Answers4

0

Use SimpleDateFormat class to format your date.

String value = "2012-01-01T08:44:36+01:00";
String date = null;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try
{
    Date d = format.parse(value);
    date = format.format(d);
}
catch (ParseException ex)
{
    System.out.println(ex);
}
return date

More info on http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

Sunil Kumar B M
  • 2,735
  • 1
  • 24
  • 31
  • SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss"); String time1=ft.format(time); I tried with this but without success. It throws me an exception – Veljko Feb 06 '12 at 08:42
  • `SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); try { Date d = format.parse(value); this.value = format.getCalendar(); this.length = value.length(); } catch (ParseException ex) { System.out.println(ex); }` – Sunil Kumar B M Feb 06 '12 at 08:46
  • Thanks Sunil for the answer. Is return from this code "d"? Because I need to return it as string? Will this be enough "d.toString();" – Veljko Feb 06 '12 at 08:52
  • `SimpleDateFormat.format()` returns the `String`. Have a look at the code. I've updated it. – Sunil Kumar B M Feb 06 '12 at 09:02
  • Thanks for your response but I can not use this "value" and "length" method. I have as input parameter some string **time** (with T and +01:00) and I want it to convert it to date time. So how to do that? I do not want with time in this moment which I supose your method does. Thanks – Veljko Feb 06 '12 at 09:34
  • Got a bit confused. `value` variable is not a `Calender` type but a `String` type only. The above code will serve your purpose. Try it now – Sunil Kumar B M Feb 06 '12 at 09:41
  • format.getCalender returns Calender object so this.value is Calender object and I can not compile my code until I set at the beginning of the class private Calendar value; You can see it in attachment http://www.dodaj.rs/f/3f/tX/1OGbNIWb/string.jpg that gives me an error – Veljko Feb 06 '12 at 10:01
  • Hi, I can compile now but it gives me an exception java.text.ParseException: Unparseable date: "2012-02-06T11:22:50+01:00" – Veljko Feb 06 '12 at 10:34
  • What is T in between date and time?? – Sunil Kumar B M Feb 06 '12 at 10:36
  • I think it is remark for Time Zone. In database date is in correct format datetime 2012-02-06 11:22:50. Then system automatically creates in XML file this 2012-02-06T11:22:50+01:00 and I must get it out from there in format yyyy-MM-dd hh:mm:ss – Veljko Feb 06 '12 at 10:38
0

But remember that, SimpleDateFormat is not thread-safe. You can use FastDateFormat from apache: FastDateFormat

Usage:

// create a formatter that simply prints the year and month
FastDateFormat formatter =
    new FastDateFormat( "yyyy-MM",
                         TimeZone.getDefault( ),
                         Locale.getDefault( ) );
// output equals "2012-02"
String output = formatter.format( new Date( ) );

Parsing date:

FastDateFormat formatter = FastDateFormat.getInstance("yyyy-MM");
String s = "2012-01-01T08:44:36+01:00";
try {
    Object o = DateUtils.parseDate(s, new String[]{"yyyy-MM-dd'T'HH:mm:ss+01:00"});
    // output equals "2012-01"
    String output = formatter.format(o);
} catch (ParseException e) {
    System.err.println("Bad date: " + s);
}
kornero
  • 1,109
  • 8
  • 11
  • Thanks but I do not want currently time. I want time which I give as some parameter String time=2012-01-01T08:44:36+01:00; Does it can be done with this FastDateFormat? – Veljko Feb 06 '12 at 09:38
  • You should parse your date first. – kornero Feb 06 '12 at 10:17
0

Sometimes the simplest is best

String s = "2012-01-01T08:44:36+01:00";
// s2 = "2012-01-01 08:44:36"
String s2 = s.substring(0,10) + ' ' + s.substring(11, 19);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Thanks for response this is useful but my colleague says me that it is not good for the performance of the system because there will be a lots of dead strings in memory during the time – Veljko Feb 06 '12 at 09:39
  • 1
    If you are worried about performance, using SimpleDateFormat or regular expressions creates many more objects and is much slower. – Peter Lawrey Feb 06 '12 at 09:47
0

Sometimes the simplest is best

String s = "2012-01-01T08:44:36+01:00";
// s2 = "2012-01-01 08:44:36"
String s2 = s.substring(0,10) + ' ' + s.substring(12, 8);

This way may produce bugs with indexes, that may appeare, as in your example :-) Also in case of some bad string you will spend a lot of time while finding the bug, because this simple way don't have any checks for input string.

Right indexes:

String s2 = s.substring(0,10) + ' ' + s.substring(11, 19);

If you want to work with date as with string, I prefer using RegXP:

    // You can parse your xml output using regXp:
    String s = "<root><date>2012-01-01T08:44:36+01:00</date></root>";

    Pattern pattern = Pattern.compile("(.+)(T)(.+)([+-])");
    Matcher matcher = pattern.matcher(s);

    if (matcher.find()) {
        System.out.println(matcher.group(1) + ' ' + matcher.group(3));
    } else {
        System.err.println("Bad date: " + s);
    }

Speed testing:

public class tempClass {

    static final String s = "2012-01-01T08:44:36+01:00".intern();
    static String formattedDate = null;
    static final int loop = 5 * 1000;
    static final String[] patterns = new String[]{"yyyy-MM-dd'T'HH:mm:ss+01:00".intern()};

    public static void main(String[] args) throws ParseException, InterruptedException {
        testSimpleWay();
        testRegXp();
        testSimpleDateFormat();
        testFastDateFormat();
    }

   private static void testRegXp() {
        Pattern pattern = Pattern.compile("(.+)(T)(.+)([+-])");
        Matcher matcher;

        final long timeStamp = System.currentTimeMillis();            
        for (int i = 0; i < loop; i++) {
            matcher = pattern.matcher(s);
            if (matcher.find()) {
                formattedDate = matcher.group(1) + ' ' + matcher.group(3);
            } else {
                System.err.println("Bad date: " + s);
            }
        }
        System.out.println("Duration of RegXP: " + (System.currentTimeMillis() - timeStamp) + " ms.");
    }

    private static void testSimpleWay() {
        long timeStamp = System.currentTimeMillis();
        for (int i = 0; i < loop; i++) {
            formattedDate = s.substring(0, 10) + ' ' + s.substring(11, 19);
        }
        System.out.println("Duration of Simple way: " + (System.currentTimeMillis() - timeStamp) + " ms.");
    }

    private static void testSimpleDateFormat() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        final long timeStamp = System.currentTimeMillis();
        for (int i = 0; i < loop; i++) {
            try {
                formattedDate = simpleDateFormat.format((Date) DateUtils.parseDate(s, patterns));
            } catch (ParseException ex) {
                System.err.println("Bad date: " + s);
            }
        }
        System.out.println("Duration of SimpleDateFormat: " + (System.currentTimeMillis() - timeStamp) + " ms.");
    }

    private static void testFastDateFormat() {
        FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

        final long timeStamp = System.currentTimeMillis();
        for (int i = 0; i < loop; i++) {
            try {
                formattedDate = fastDateFormat.format((Date) DateUtils.parseDate(s, patterns));
            } catch (ParseException e) {
                System.err.println("Bad date: " + s);
            }
        }
        System.out.println("Duration of FastDateFormat: " + (System.currentTimeMillis() - timeStamp) + " ms.");
    }

Output:

Duration of Simple way: 5 ms.
Duration of RegXP: 20 ms.
Duration of SimpleDateFormat: 114 ms.
Duration of FastDateFormat: 65 ms.
kornero
  • 1,109
  • 8
  • 11