0

I have a text field which displays date strings in this format: MM/dd/yyyy (e.g. 03/12/2012) ... And I want to convert it to this format: yyyy-MM-dd (e.g. 2012-03-12) ... So basically the conversion I need is:

MM/dd/yyyy ---> yyyy-MM-dd

Both data types would be strings ..

Whats the quickest way to do this ?

Ahmad
  • 12,886
  • 30
  • 93
  • 146

10 Answers10

6

I would just use a separate format object (i.e. SimpleDateFormat or DateFormat) and apply it to the same Date object.

It doesn't make much sense to convert between string representations of the same object; it makes more sense to provide different views.

Moonbeam
  • 2,283
  • 1
  • 15
  • 17
5
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date = (Date)formatter.parse("03/12/2012");

formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(date); //yyyy-MM-dd
aleroot
  • 71,077
  • 30
  • 176
  • 213
3

You asked for the quickest way:

@Test
public void test() {
    assertEquals("2016-10-29", convert("10/29/2016"));
}

// MM/dd/yyyy ---> yyyy-MM-dd
public static String convert(final String date) {
    // We assume that the format is guaranteed to be correct,
    // otherwise add validation logic
    final char[] chars = new char[10];
    date.getChars(0, 5, chars, 5); // MM/dd
    date.getChars(6, 10, chars, 0); // yyyy
    chars[4] = chars[7] = '-';
    return new String(chars);
}
rmuller
  • 12,062
  • 4
  • 64
  • 92
3

You could just do it with string fiddling - but personally I'd parse to some date/time representation, then format back again.

With the standard libraries, you can use SimpleDateFormat for that. Personally I'd use Joda Time and parse to a LocalDate with a DateFormatter (then format with another one). You'd create the DateTimeFormatter instances with DateTimeFormat. Note that Joda Time's format classes are thread-safe; the Java standard library ones aren't.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

You can simply use String#split like this:

String str = "03/12/2012";
String arr[] = str.split("/");
String newDate = arr[2] + '-' + arr[0] + '-' + arr[1];
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You can find a good example of what you want there :

SimpleDateFormat Converting

You just have to use SimpleDateFormat in order to make that.

ChapMic
  • 26,954
  • 1
  • 21
  • 20
1

Because of "I have a text field which displays date strings", you should simply just use normal DateFormat. It is highly unlikely that you would notice any measurable difference in performance of your application by optimizing date formatting. So just go for something like (and maybe reuse parser and formatter as long as you are in single thread):

SimpleDateFormat parser = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String date = "03/12/2012";
Date d = parser.parse(date);
String result = formatter.format(d);

If you sometime face the situation where performance of this really matters, then you can go for this kind of implementation (not that many instances of String created as with subtring-approaches):

String date = "03/12/2012";
char[] cc = date.toCharArray();
char[] converted = {cc[6], cc[7], cc[8], cc[9], '-', 
                    cc[0], cc[1], '-', cc[3],cc[4]};
String result = new String(converted);
Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
0

java.time

Quickest to write:

LocalDate.parse( 
    "03/12/2012" ,
    DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) 
).toString()

Your desired output happens to comply with the ISO 8601 standard for formatting date-time strings. The java.time classes use those standard formats when parsing and generating strings representing their value.

The java.time.LocalDate class is built into Java 8 and later, and represents a date-only value without time-of-day and without time zone.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

Quickest to execute?

If we cache the DateTimeFormatter, the cost of each parse-a-string-to-generate-a-string takes a third of a microsecond, 300-400 nanoseconds, when running in NetBeans 8.2 under Java 8 Update 111 on a MacBook Pro (Retina, 15-inch, Late 2013) (2.3 GHz Intel Core i7 processor) (16 GB 1600 MHz DDR3) (macOS El Capitan).

DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MM/dd/uuuu" );
int limit = 100_000_000; // Number of iterations of parsing a string to generate a string.
long start = System.nanoTime ();
for ( int i = 0 ; i < limit ; i ++ ) {
    String s = LocalDate.parse ( "03/12/2012" , f ).toString ();
}
long stop = System.nanoTime ();
long elapsedNanos = ( stop - start );
long elapsedSeconds = TimeUnit.NANOSECONDS.toSeconds ( elapsedNanos );
long eachNanos = ( elapsedNanos / limit );
System.out.println ( "For limit of " + limit + " took seconds: " + elapsedSeconds + " and each iteration took nanoseconds: " + eachNanos );

For limit of 100000000 took seconds: 33 and each iteration took nanoseconds: 332

Instantiating the DateTimeFormatter seems to take about 200 nanoseconds, nearly doubling the execution time. Change one line of code above, to replace the argument f.

    String s = LocalDate.parse ( "03/12/2012" , DateTimeFormatter.ofPattern ( "MM/dd/uuuu" ) ).toString ();

For limit of 100000000 took seconds: 54 and each iteration took nanoseconds: 542


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

Perhaps

String date = "MM/dd/yyyy";
String date2 = date.substring(6)+'-'+date.substring(3,5)+'-'+date.substring(0,2);
System.out.println(date2);

prints

yyyy-dd-MM

It will also re-order any correct (or incorrect date)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

If the incoming format is guaranteed, then

String inputDate = "12/31/1970"; // for example
String outputDate = inputDate.substring(6, 10) + '-' 
    + inputDate.substring(0, 2) + '-' 
    + inputDate.substring(3, 5);

is probably the fastest executing.

If the incoming format isn't guaranteed, I'd parse and format using DateFormat as suggested by the other answers.

Andrew Spencer
  • 15,164
  • 4
  • 29
  • 48