Mohammed haneef
Mohammed haneef

Reputation: 117

Replace substring in a particular postion

String date = "2012-11-28 12:30:30";

I want to replace the date to 2012-11-28 12:00:00 by using String.replace method as:

String replacedDate = date.replace(date.substring(14, 19), "00:00");

It is working fine but if date is:

String date = "2012-11-28 18:18:18";

Using the above method the result will be 2012-11-28 00:00:28 but I want the output to be 2012-11-28 18:00:00 instead.

Upvotes: 3

Views: 113

Answers (5)

Daniela Mogini
Daniela Mogini

Reputation: 299

I think your solution doesn't work because the replace method has this signature

public String replace(char oldChar, char newChar)

not

public String replace(String oldChar, String newChar)

This answer is meant at understanding the problem, to solve it, consider the other great answers!

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838196

You don't need to use the String.replace method here. If you know the exact indices that you wish to replace and you are sure that they will always be the same then you can use substring and string concatenation:

String date = "2012-11-28 12:30:30";
date = date.substring(0, 14) + "00:00";

See it working online: ideone

Note: if your string is really represents a date, consider using a variable of type Date instead of String.

Upvotes: 5

SomeJavaGuy
SomeJavaGuy

Reputation: 7347

You could also ask for the first first ':' and add the "00:00" then

String date="2012-11-28 18:18:18";
int i = date.indexOf(':');
String format = date.substring(0,i+1) + "00:00";

Upvotes: 0

assylias
assylias

Reputation: 328608

You could use a Date parser that ignores the minutes and seconds instead of manipulating the string directly:

String s = "2012-11-28 12:30:30";
//skip the minutes, seconds
Date date = new SimpleDateFormat("yyyy-MM-dd HH").parse(s); 

String result = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println("result = " + result);

Bonus: if the date is not in the expected format you will get a useful exception

Upvotes: 4

Brian Agnew
Brian Agnew

Reputation: 272277

It's a date/time. Treat it as such by parsing the above into a suitable date/time object and manipulating it using date/time-related methods. That way you don't have to rely on substrig/regexps etc. and you won't run the risk of creating an invalid date/time reference.

e.g. use SimpleDateFormat and Calendar, or Joda-Time for a more intuitive and robust API.

Currently you have a stringly-typed system, not a strongly-typed system.

Upvotes: 1

Related Questions