How to delete all the characters after one character in the String? - java

I have a String which contains a date, for example "01-01-2012", then an space and then the time "01:01:01". The complete string is: "01-01-2012 01:01:01"
I would like to extract only the date from this string so at the end I would have "01-01-2012" but don't know how to do this.

Four options (last two added to make this one answer include the options given by others):
Parse the whole thing as a date/time and then just take the date part (Joda Time or SimpleDateFormat)
Find the first space using indexOf and get the leading substring using substring:
int spaceIndex = text.indexOf(" ");
if (spaceIndex != -1)
{
text = text.substring(0, spaceIndex);
}
Trust that it's valid in the specified format, and that the first space will always be at index 10:
text = text.substring(0, 10);
Split the string by spaces and then take the first result (seems needlessly inefficient to me, but it'll work...)
text = text.split(" ")[0];
You should consider what you want to happen if there isn't a space, too. Does that mean the data was invalid to start with? Should you just continue with the whole string? It will depend on your situation.
Personally I would probably go with the first option - do you really want to parse "01-01-2012 wibble-wobble bad data" as if it were a valid date/time?

String input = "01-01-2012 01:01:01";
String date = d.split(" ")[0];

Try this:
String date = s.substring(0, s.indexOf(" "));
Or even (because the length is fixed):
String date = s.substring(0, 10);
Or use StringUtils.substringBefore():
String date = StringUtils.substringBefore(s, " ");

Lots of ways to do this, a very simple method is to split the String at the space and use the first part (which will be the date):
String dateTime = "01-01-2012 01:01:01";
String date = dateTime.split(" ")[0];

You can use String.split() and take only the relevant String in your resultng String[] [in your example, it will be myString.split(" ")[0]

In that case where only one space is in the string, you can use String.split(" "). But this is a bad practice. You should parse the date with a DateFormat
.

You can use substring to extract the date only:
String thedatetime = "01-01-2012 01:01:01";
String thedateonly = thedate.substring(0, 10);
You should really read through the javadoc for String so you are aware of the available functions.

If you know in advance this is the format of the string, I'd do this:
public String getDateOnly(String fullDate){
String[] spl = fullDate.split(" ");
return spl[0];
}

You can do it either using string manipulation API:
String datetime = "01-01-2012 01:01:01";
int spacePos = datetime.indexOf(" ");
if (spacePos > 0) {
String date = datetime.substring(0, spacePos - 1);
}
or using regular expression:
Pattern p = Pattern.compile("(\\d{2}-\\d{2}-\\d{4})");
String datetime = "01-01-2012 01:01:01";
Matcher m = p.matcher(datetime);
if(m.find()) {
String date = m.group(1);
}
or using SimpleDateFormat
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = fmt.parse(datetime);
Calendar c = Calendar.getInstance();
c.setTime(date);
String date = c.getDayOfMonth() + "-" + c.getMonth() + "-" + c.getYear();

Use String.substring(int, int). If you are interested in the value of the date and time, then use SimpleDateFormatter to parse your string.

myString.substring(0,10);
If your string is always in that format (2 digits, minus, 2 digits, minus, 4 digits, space etc...) then you can use substring(int beginIndex, int endIndex) method of string to get what you want.
Note that second parameter is the index of character after returning substring.

If you want to explode the complete date from the string use this method.
/**
* #param dateTime format string
* #param type type of return value : "date" or "time"
* #return String value
*/
private String getFullDate(String dateTime, String type) {
String[] array = dateTime.split(" ");
if (type == "time") {
System.out.println("getDate: TIME: " + array[1]);
return array[1];
} else if (type == "date") {
System.out.println("getDate: DATE: " + array[0]);
return array[0];
} else {
System.out.println("NULL.");
return null;
}
}
Otherwise if you want only the date for explample 01-01-2012
use this:
/**
* #param datetime format string
* #return
*/
private String getOnlyDate(String datetime) {
String array[] = datetime.split("-");
System.out.println("getDate: DATE: " + array[0]);
return array[0];
}
I hope my answer will help you.

Related

Separate string array elements with next line \n or separator

I need some help with these strings. My code is:
String string = database.getCurrentDate();;
String[] array = string.split("[.]", 0);
String date = array[0] + "." + array[1];
String string1=database.getCurrentHour();
String[] array1=string1.split("[:]",0);
String hour=array1[0]+":"+array1[1];
String finalString=date+hour;// finalString is 28.0310:45
I need that finalString to be:
date
hour//on next line
example:
28.03//date
10:45//hour
The point is that I need the hour to be displayed on the next line, under date.
Thank you!
String finalString = date + "\n" + hour
Don't work if you display this?

reading a whole date and time with spaces in a file

this question may have been asked before but didn't find any clue for my problem here,
here is my problem : I have a file that is like this :
abc fg Sat Jan 08 19:06:21 IST 2022 4 4.0
here is my code that reads from the file :
BufferedReader read4 = new BufferedReader(new FileReader("shortDelvsFile.txt"));
while ((s = read4.readLine()) != null) {
token = new StringTokenizer(s);
double str1 = Double.parseDouble(token.nextToken());
Integer str2 = Integer.parseInt(token.nextToken());
while (token.hasMoreTokens()) {
System.out.println(convert(token.nextToken()));
}
ShortDeliveries d = new ShortDeliveries(token.nextToken(), token.nextToken(),
convert(token.nextToken()), str2, str1);
shortDelvss.add(d);
}
System.out.println("the short deliveries are : " + shortDelvss);
read4.close();
// this function is to convert the string to date
public static Date convert(String s) throws ParseException {
Date date = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH).parse(s);
System.out.println(date);
return date;
}
now i want each ``token.nextToken();``` inside the ShortDeliveries to be like this:
token.nextToken() = fg
convert(token.nextToken()) = Sat Jan 08 19:06:21 IST 2022
str1 = 4
str2 = 4.0;```
the problem is that in convert(token.nextToken()) it doesn't take the whole date because tokenizer reads until the first space how can i fix that?
In case you know the date will always start with the day of week (e.g. Sat, Sun...), you can create a method to check if the current token is a known day.
In case this is a week day, collect the following 6 tokens (or whatever tokens count you need to form a valid date) and send them together as String to your convert method.
if (isDayOfWeek(token)) {
List<String> dateTokens = getNextTokens(token, 6);
String dateString = String.join(" ", dateTokens);
Date date = convert(dateString);
}
private boolean isDayOfWeek(String dayString) {
Locale locale = Locale.getDefault();
return Arrays.stream(DayOfWeek.values())
.map(day -> day.getDisplayName(TextStyle.SHORT, locale))
.anyMatch(dayString::equals);
}
private List<String> getNextTokens(StringTokenizer token, int tokenCount) {
return IntStream.rangeClosed(1, tokenCount)
.mapToObj(i ->token.nextToken())
.collect(Collectors.toList());
}
"s" is just a string that represents one line of your data
If you process it like a variable instead of a stream, you can use split.
There are several ways to do this, my preferences is as follows:
String parts_of_s = s.split(" ");
String s1 = s[0]; // you can in-line converting to double as you did above
String s2 = parts_of_s[1];
String remaining_string = s.substring(s1.length()+1 + s2.length()+1); // length indexes at zero
String string_date = remaining_string.substring(0, 28); // since you know how many characters there are in the format
String s3 = parts_of_s[8];
String s4 = parts_of_s[9];
If you're dealing with super-long lines of data where efficiency matters (you probably won't), you could pursue other avenues:
read the next 28 characters
read the next 6 tokens and concatenate with a space

Check if an intermediate string starts-ends with certain pattern and update the string

If I have a string like :
String str = "startDate:23/04/2016;endDate:;renewDate;"
Required multiple operation on the string.I need to get a String and extract different sub-strings using a delimiter (";") then again extract different sub-strings to form a key-value using a delimiter (":"). If against the key their is no value present the update with diff-diff default value like ("01/01/2000","01/01/1900" since both are of type Date).
if you notice for renewDate field their is no separator (":") in this case we need to append the separator along with default value (:01/01/1900) so that my expected result would be like :
String str = "startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;"
I have tried below regex but it is not working for all scenario :
String regExpression = "(?<=\\bendDate:)[;]+"
str = str.replaceAll(regExpression , "01/01/2000");
Can any one guide me how to achive the result using regex.Thanks!!!!!
As Tim said we can use regex pattern to replace the value. Adding to his answer, the only change I recommend to add colon(:) as optional in pattern used for both renewDate and endDate in text.
String endDate = "01/01/2000";
String renewDate = "01/01/1900";
String str = "startDate:23/04/2016;endDate:;renewDate;";
str = str.replaceAll(";endDate:?;", ";endDate:"+endDate+";");
str = str.replaceAll(";renewDate:?;", ";renewDate:"+renewDate+";");
System.out.println(str);
This will give the output as below
startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;
Using a regex replacement, we can try:
String endDate = "01/01/2000";
String renewDate = "01/01/1900";
String str = "startDate:23/04/2016;endDate:;renewDate:;";
String output = str.replaceAll("\\bendDate:;", "endDate:" + endDate + ";")
.replaceAll("\\brenewDate:;", "renewDate:" + renewDate + ";");
System.out.println(output);
This prints:
startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;
The logic here is to only target empty end and renew date fields, including default values if needed.
Alternatively, separate strings based on your first delimiter ; and then :.
String str = "startDate:23/04/2016;endDate:;renewDate;";
String dates[] = str.split(";");
for(String date : dates){
String default[] = date.split(":");
output.append(default[0] + ":" + (default.length > 1 ? default[1] : defaultDate));
}

How to get substring from the given string?

I have read whole xml file as single string using class.The output is
String result=<?xml version="1.0"?><catalog><book id="bk101"><part1><date>Fri Apr 05 11:46:46 IST 2013</date><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price> <publish_date>2000-10-01</publish_date></part1></book></catalog>
Now i want to replace date value.so first i want to extract date from the string and replace new value.I have following code,
Date date=new Date()
String str=result.substring(result.indexOf("<date>"));
It displays whole string from date tag to end tag.
How to extract date tag and replace it?
This here gets the contents of the tags using regex... but as for replacing it - I'll get back to you.
String result = "<?xml version=\"1.0\"?><catalog><book id=\"bk101\"><part1><date>Fri Apr 05 11:46:46 IST 2013</date><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price> <publish_date>2000-10-01</publish_date></part1></book></catalog>";
String pattern = ".*(?i)(<date.*?>)(.+?)(</date>).*";
System.out.println(result.replaceAll(pattern, "$2"));
Cheers
String str=result.substring(result.indexOf("<date>") ,result.indexOf("</date>")+"</date>".length());
String#substring(int beginIndex)
Returns a new string that is a substring of this string. The substring
begins with the character at the specified index and extends to the
end of this string.
String#substring(int beginIndex,int endIndex)
Returns a new string that is a substring of this string. The substring
begins at the specified beginIndex and extends to the character at
index endIndex - 1. Thus the length of the substring is
endIndex-beginIndex.
Edit: Oh, you wanted it in java. This is the C# solution =)
You can solve this by replacing the entire date including the tag.
You have two dates in your XML so to be sure that you will not replace both of them you can do it like this.
int index1 = result.IndexOf("<date>");
int index2 = result.IndexOf("</date>") - index1 + "</date>".Length;
var stringToReplace = result.Substring(index1, index2);
var newResult = result.Replace(stringToReplace, "<date>" + "The Date that you want to insert" + "</date>");
Just the value:
String str = result.substring(result.indexOf("<date>") + "<date>".length(),
result.indexOf("</date>"));
Including the tags:
String str = result.substring(result.indexOf("<date>"),
result.indexOf("</date>") + "</date>".length());

remove : in 12:45 (java)

time 12:45
i want to remove : in java .. i just need 1245 ..How can i do that?
String time = "12:45".replace( ":", "" ); // "1245"
If you have Apache Coomons Lang in your classpath, and you are not sure that time is not null, you could use StringUtils:
time = StringUtils.remove( time, ":" );
this way is more compact than writing
if ( time != null ) {
time = time.replace( ":", "" );
}
There is the "replace" method.
s = s.replace(':','');
If you want to get fancy:
s = s.replaceAll("[^a-zA-Z0-9]", "");
This will remove all non-alpha numeric characters (including your ':')
All right there in the JavaDoc.
If "12:45" is a string, then just use "12:45".replaceAll(":", "").
String strTime = "12:45";
strTime.replace(':','');
For the easiest method, use replace:
String time = "12:45";
time = time.replace(':', "");
but you can use regular expressions:
Pattern pattern = new Pattern("(\\d{1,2}):(\\d{1,2})");
Matcher matcher = pattern.matcher("12:45");
String noColon = matcher.group(1) + matcher.group(2);
or the String API:
String time = "12:45";
int colonIndex = time.indexOf(':"';
String noColon = time.substring(0, colonIndex) +
time.substring(colonIndex + 1, time.length);
Like what others told, a method as simple as String's replace should suffice, but since i suspect your input is a date, have a look at SimpleDateFormat too.

Categories